Need some help?

I'm usually available for small jobs or problem solving with jQuery or css. Just get in touch.

Simple jQuery image slider

Bored this morning so I thought I would adapt my jQuery image crossfade cycler into an image slider. Tested in IE6/7/8, Firefox 3, Chrome, Opera 9/10, Safari 4, all on Windows XP, and Safari 5 on Mac OS X/Snow Leopard. You might also want to have a look at my image and caption slider demo.

The demo

Hoverfly on a green leaf Fly on a pink flower Insect on a leaf Fly

The code

Here’s the necessary css – just to show the important bits – you’ll need to add some more to position and style as required:

#portfolio_slider{position:relative;overflow:hidden}
#portfolio_slider img{position:absolute;left:100%}
#portfolio_slider img.active{left:506px}

And here’s the javascript:

function slideImages(){
      var $active = $('#portfolio_slider .active');
      var $next = ($('#portfolio_slider .active').next().length > 0) ? $('#portfolio_slider .active').next() : $('#portfolio_slider img:first');
      $next.css('z-index',2);//set the z-index so the image will slide across the top of  current one
      $active.css('z-index',1);//and set the current active image so it's below> 
      $next.animate({left:0},"slow",function(){//slide in the next image
              $active.removeClass('active').css('left',"506px");//when the slide's finished, reset the previous active image
              $next.addClass('active');//and set the new image to active
        });
    }

    $(document).ready(function(){
      // run every 7s
      setInterval('slideImages()', 7000);
    })

The logic

The slider div is set with overflow:hidden. All the images are loaded with the page and positioned absolutely within the slider div, with left:506px which is the width of my slider, so the images aren’t visible. One image is initially set with a class of “active” which sets left:0 , so that it is visible.

Then, using jQuery, I’m identifying the active image, and then the next image down. I’m doing this via the jQuery .next() method. If there isn’t a next image – if we’re at the end of the images – I’m selecting the first image instead using .first().

Now, once I’ve identified the next image, I’m assigning z-index=2 to this image, and z-index=1 to the active image, so that the next image will slide across the top of the active image.

Then, I’m animating the next image using its left property. When this completes I’m removing the class of the previously active image and moving it back outside the slider so it’s ready to slide in again, and I’m setting the new image to active.

Finally, all of this code is sitting in a function which I’m calling every seven seconds via setInterval().

One response to “Simple jQuery image slider”

  1. Lawrence Khan says:

    Fantastic

Useful? Interesting? Leave me a comment