Timeline

by samselikoff

HTML

<div class="timeline"></div>

CSS

.timeline {
    height: 100px;
}

line {
    stroke-width: 2px;
    stroke: black;
}

.axis path {
    fill: none;
    stroke: black;
    stroke-width: 2px;
}

JavaScript

var chart = new Timeline(),
    data = ['20130525', '20130606'];

d3.select('.timeline').data([data]).call(chart);


function Timeline() {

    var margin           = {top: 20, right: 20, bottom: 20, left: 20},
        scale            = d3.time.scale(),
        customTimeFormat = d3.time.format("%b %e"),
        axis             = d3.svg.axis().scale(scale).ticks(7).tickFormat(customTimeFormat),
        parseDate        = d3.time.format("%Y%m%d").parse;
            

    function chart(selection) {
        selection.each(function(dates)
        {
            var width = selection[0][0].offsetWidth-margin.left-margin.right,
                height = selection[0][0].offsetHeight-margin.top-margin.bottom,
                begin = parseDate(dates[0]),
                end = parseDate(dates[1]);
            
            var data = [];
            while (begin < end) {
                data.push( new Date(begin.getTime()) );
                begin.setDate( begin.getDate() + 1 );
            }
            
            // Update the scale
            scale
                .domain( d3.extent(data) )
                .range( [0, width] );

            // Select the svg element, if it exists.
            var svg = d3.select(this).selectAll("svg").data([data]);

            // Otherwise, create the skeletal chart.
            var gEnter = svg.enter().append("svg").append("g");
            gEnter.append("g").attr("class", "axis").call(axis);
            gEnter.append("line").

            // Update the outer dimensions.
            svg.attr("width", width + margin.left + margin.right)
                .attr("height", height + margin.top + margin.bottom);

            // Update the inner dimensions.
            var g = svg.select("g")
                .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

            // Update the chart's axis.
            g.select(".axis")
                .attr("transform", "translate(0," + (height - 10) + ")");
            
     ...