< ISM Blog

Make your image slider loop - use jQuery to create the slide effect between last and first slides

In the previous post you learned how to make a responsive image slider from scratch. The tutorial was deliberately kept simple and as a result some desirable features left out. In this post jQuery (JavaScript) is used to enable cycling of the slides, such that there will be a slide transition between the last and first slides. The result will be an image slider that can continuously loop.

The HTML and CSS will remain unchanged; only slider.js requires editing. It is assumed that you have already completed the steps in the How to Make a Responsive Image Slider using jQuery and CSS. If not then either complete them now or if you want to fast forward, download the source files and images into a directory and continue from here.

You can download the completed slider.js file or add the lines yourself.

1. Use jQuery's clone method to copy the first and last slide DOM elements:

The last li element is cloned and prepended as the first child of the ul and first li element is cloned and appended as the last child of the ul.

var first_slide = ul.find("li:first-child"); var last_slide = ul.find("li:last-child"); // Clone the last slide and add as first li element last_slide.clone().prependTo(ul); // Clone the first slide and add as last li element first_slide.clone().appendTo(ul);

Now the 3 slides have become 5.

2. Set the ul's left margin

The left margin of the ul is programmatically set so that the cloned slide is hidden beyond the left edge and slide 1 is initially visible.

ul.css("margin-left", "-100%");

3. Update the slide function

Now margin_left_pc is set to take into account the prepended cloned li element and two conditional blocks are added within the callback of animate:

function slide(new_slide_index) { var margin_left_pc = (new_slide_index * (-100) - 100) + "%"; ul.animate({"margin-left": margin_left_pc}, 400, function() { // If new slide is before first slide... if(new_slide_index < 0) { ul.css("margin-left", ((slide_count) * (-100)) + "%"); new_slide_index = slide_count - 1; } // If new slide is after last slide... else if(new_slide_index >= slide_count) { ul.css("margin-left", "-100%"); new_slide_index = 0; } slide_index = new_slide_index }); }

The code in the callback is executed after the slide animation has completed. If the new slide's index is less than zero then the user has paged left beyond slide 1 and so the ul element's margin-left property is set so the last slide is visible. Else if the new slide's index is greater or equal to the number of slides (3) then the user has paged right beyond slide 3 and so the left-margin is set so the first slide is visible. It is this functionality that creates the illusion the slider can be infinitely paged left of right.

Resources

Download the completed source files and images (right-click and save):

Share