How To Build a Content Slider with Jquery

I was recently looking to build a content slider for a home page of a project.

You know the kind I’m talking about where a certain area of the page constantly scrolls through different messages.

Of course, there are ton’s of plugins out there that do this and a lot more. But, I wanted something lightweight and easy to maintain. Plus, I’m always a little leary of using plugins in general.

So, what follows below is a JQuery content slider that rotates through a series of elements on the page, and allows the user to stop the animation or return to a previous or future animation.

The requirements are as follows:

  • Must use appropriate HTML (a list of things to scroll through).
  • Must degrade nicely if no javascript available (just hold on the first element).
  • User must be able to select any slide in the sequence at any time.
  • Upon selection the animation must start automatically.

First setup your HTML. I used a unordered list to be semantically correct. The script will scroll through this list of elements displaying each one.

<ul id="rotator">
<li id="first">
    <div><!--HTML to Display Goes HERE--></div>
</li>
<li>
    <div><!--HTML To Display Goes HERE--></div>
</li>
<li>
    <div><!--HTML To Display Goes HERE--></div>
</li>
</ul>
<ul id="rotator_pager">
    <li></li>
    <li></li>
    <li></li>
</ul>

Basically, this sets up two Unordered lists. The first list contains that content that we want to scroll through.

The second list setups some small selector blocks that coorespond to the content that is rotating through (what the user clicks on to select a certain piece of content while it is rotating)

What follows is the JQuery that does all the heavy lifting:

$(document).ready(function () {

var j = 0;
var fadetime = 700;
var delay = 3000; //millisecond delay between cycles
function cycleThru() {
    var jmax = $("ul#rotator li").length - 1;
    $("ul#rotator_pager li:eq(" + j + ")").css("background-color", "#660000");

    $("ul#rotator li:eq(" + j + ")").fadeIn(fadetime).delay(delay);

    $("ul#rotator li:eq(" + j + ")").fadeOut(fadetime, function () {
        $("ul#rotator_pager li:eq(" + j + ")").css("background-color", "");
        (j == jmax) ? j = 0 : j++;
        cycleThru();
    });

};

var items = $("ul#rotator_pager li").click(function () {
    $("ul#rotator li:eq(" + j + ")").clearQueue();
    $("ul#rotator li:eq(" + j + ")").stop();
    $("ul#rotator li:eq(" + j + ")").hide();
    $("ul#rotator_pager li:eq(" + j + ")").css("background-color", "");
    j = items.index(this);
    cycleThru();

});

cycleThru();

});

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>