Friday, 5 April 2013

jQuery: Slideshow Auto-Advancing


One of the most requested improvements over the tutorials presented on this site, when it comes to slideshows, is the ability to have the slides advance automatically. It is actually not that difficult to achieve this effect, and to demonstrate it, in this short tutorial we are going to make our HTML5 Slideshow auto advance with a few lines of jQuery.

The Idea

As our slideshow already has a previous / next arrows, we can just have a JavaScript function execute periodically and “click” the next arrow for us. With jQuery we can easily simulate any event on any element with the help of the trigger() method like so:
$('#nextArrow').bind('click',function(){
    alert("Clicked!");
});

$('#nextArrow').trigger('click');

// or alternatively:
// $('#nextArrow').click();


The snippet above will fire all the handlers for the click event and output the alert message. In the case with the slideshow, we don’t care what happens behind the scenes nor how the animation works, we just simulate a click with the mouse.  This means that we could as well have the auto advancing script as an external, separate file.
Combined with the setTimeout() JavaScript function we have all the tools necessary to make our slideshow transition automatically between the slides.

The Implementation

Bearing the above in mind, here is the complete auto advance code.

autoadvance.js


$(window).load(function(){

// The window.load event guarantees that
// all the images are loaded before the
// auto-advance begins.

var timeOut = null;

$('#slideshow .arrow').click(function(e,simulated){

// The simulated parameter is set by the
// trigger method.

if(!simulated){

// A real click occured. Cancel the
// auto advance animation.

clearTimeout(timeOut);
}
});

// A self executing named function expression:

(function autoAdvance(){

// Simulating a click on the next arrow.
$('#slideshow .next').trigger('click',[true]);

// Schedulling a time out in 5 seconds.
timeOut = setTimeout(autoAdvance,5000);
})();

});


Notice that we are passing an array parameter to the trigger method on line 28. The element of this array is available to us as the simulated parameter on line 9. This helps us distinguish fake clicks from real ones. If a real one does occur, we stop the auto-advancement by clearing the timeout.

To Wrap Up

To use this script you just need to replace the selectors for the next arrow on line 28 and for both arrows on line 9. With these modifications you will be able to use this snippet to automate any slideshow (or any kind of presentation really) on your site by just including autoadvance.js with a script tag.

No comments:

Post a Comment