A simple jQuery slider

Sometimes you need to handle custom sliders and you also need to listen for the user click event.

This is the code I eventually used, perfectible (surely), but it seems to do its job very well.

The really important parts are those in which you need to set the interval and the timeout, as well as those in which you must clear the interval and the timeout.

$(document).ready(function() {
  // time stuff
  var timer = null;
  var restartAfterSecs = 7000;
  var slideIntervalSecs = 5000;
  
  // Here you can set which are the elements to be used as slider
  var myClickableElements = 'ul#something li';
  
  // Used on eq, which is zero-indexed, therefore -1 it's ok !!
  var total = $(myClickableElements).size() -1;
  
  // The first time, starts from the second element
  var slideindex = 1;
  
  $(myClickableElements).live('click', function(e) {

    if (e.originalEvent !== undefined) {
      // --- this is a human click
      
      // you MUST clear the timeout to prevent that multiple clicks will be queued ...
      clearTimeout(timer);
      
      // ... as well as the current interval
      clearInterval(timer);
      
      // Restart the sliding waiting a bit more (probably the user needs to see the slide)
      timer = setTimeout(startSliding, restartAfterSecs);
    }

    /*
     * DOES SOMETHING COOL WITH YOUR ELEMENTS
     */
   });

  function startSliding() {
    timer = setInterval(function() {
      var el = $(myClickableElements).eq(slideindex); // Zero-indexed eq
      
      el.click();
      
      // Move the index at the FIRST element or at the next one
      (slideindex == total) ? slideindex = 0 : slideindex++;
      
    }, slideIntervalSecs);
  }

  startSliding(slideindex);
});

So, what’s happens here? When the page loads, startSliding() it’s invoked and uses the global “slideindex” value, which is 1 (the second slide). This “startSliding” function, sets an interval so that after “slideIntervalSecs” the “slideindex” will be clicked.

There is an event listener on click which do something with your DOM.

When comes a human click event (e.originalEvent !== undefined) you can stop the current sliding behaviour (using clearInterval) and then start it again, after a different amount of time (more or less, it’s up to you), using setTimeout.

But if you click multiple times on the elements, the events will be queued, and so you need to be sure that for each click also the timeout is cleared: to do that simply use clearTimeout.

An that’s it!

You can see it in action here.

In order to use Disqus to comment out you have to accept the use of third-party cookies.