jQuery slider as a timeline

Adam Tomat picture Adam Tomat · Sep 7, 2010 · Viewed 8.1k times · Source

I have just finished incorporating a jQuery accordian with a jQuery Slider. I.e.

3 pictures are displayed. The user can either use PREV or NEXT buttons to view the next/prev 3 images. They can also navigate through all the images with the slider.

The next step is to make this slider look like a timeline. The left hand side needs to start at 1970 and finish at 2010. For each item (an item is a set of 3 images in this case) I need it to show a date on the timeline.

i.e: alt text

I know I could create an image with the dates the right width apart but idealy this needs to be dynamic so more items can be put in and the timeline self updates.

Answer

aroth picture aroth · Mar 27, 2011

At a high level, the following should work:

  1. Get the total width of the slider UI element, in pixels.
  2. Divide this number by [total number of labels] - 1 to get the total number of pixels to allocate to each label.
  3. Add a series of div's immediately after the slider div with the width you got in step 2 and the float:left style.
  4. Follow everything with an empty div with the clear: both style.

Here is a basic example:

CSS

.timeline {
    width: 500px;
    border: 1px solid black;
}
.timelineEntry {
    float: left;
}
.first {
    position: relative; left: 5px;
}
.last {
    position: relative; left: -10px;
}
.clear {
    clear: both;
}

Markup

<div id="timelineContainer">
    <div class="timeline" id="slider">
        Slider UI Goes Here
    </div>
</div>
<div class="clear"></div>

JavaScript

var container = document.getElementById("timelineContainer");
var labels = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
var totalWidth = $("#slider").width();
var labelWidth = Math.floor(totalWidth / (labels.length - 1));
for (var index = 0; index < labels.length; index++) {
    var nextLabel = document.createElement("div");
    nextLabel.className = "timelineEntry";
    if (index == 0) {
        nextLabel.className += " first";
    }
    else if (index == labels.length - 1) {
        nextLabel.className += " last";
    }
    nextLabel.style.width = labelWidth + "px";
    nextLabel.innerHTML = labels[index];
    container.appendChild(nextLabel);
}