SiteKickr Web Development

Basic jQuery Rotator

There are hundreds of jQuery rotator / slideshow plugins out there, but at some point, you may decide that your needs to very specific. The code below should provide a basis for creating your own jQuery rotator. This code will also degrade gracefully if JavaScript is not enabled on a given browser.

The HTML

<div id="slide-wrapper">
    <div class="slide">
        <!-- rotating content goes here -->
    </div>
    <div class="slide initial-hide">
        <!-- rotating content goes here -->
    </div>
    <div class="slide initial-hide">
        <!-- rotating content goes here -->
    </div>
</div>

The CSS

#slide-wrapper { position: relative; height: 400px; }
#
slide-wrapper div.slide { position: absolute; }
#
slide-wrapper .initial-hide { display: none; }

The jQuery

var currentPosition = 0;
var totalSlides = 0;

$(document).ready(function() {
   
    // slides
    totalSlides = $('#slide-wrapper .slide').length;
    setTimeout('transition()', 3000);
   
});

transition = function() {
    currentPosition++;
    lastPosition = currentPosition - 1;
    if (currentPosition == totalSlides)
        currentPosition = 0;
   
    if (lastPosition < 0)
        lastPosition = totalSlides - 1;
       
    $('#slide-wrapper .slide:eq(' + lastPosition + ')').fadeOut('slow');
    $('#
slide-wrapper .slide:eq(' + currentPosition + ')').fadeIn('slow');
   
    setTimeout('transition()', 3000);
}