Home > Article > Web Front-end > How can I create an infinite image loop slider using JavaScript/jQuery?
This article discusses the best practices, such as readability, code reusability, and good coding practices, for building an Infinity-Image-Loop-Slider for a website using JavaScript/jQuery. The focus is on how to arrange the pictures to create the illusion of an unending loop slider.
One straightforward method for creating an infinite image slider is as follows: Assume you have "n" images to slide in a loop, with the first image following the nth image and vice-versa. Create a clone of the first and last images and do the following:
Regardless of the number of images, you only need to insert two cloned items at most.
Assuming all images are 100px wide and displayed within a container with overflow: hidden, display: inline-block, and white-space: nowrap, the container holding the images can be easily aligned in a row.
For n = 4, the DOM structure would appear as follows:
offset(px) 0 100 200 300 400 500 images | 4c | 1 | 2 | 3 | 4 | 1c /* ^^ ^^ [ Clone of the last image ] [ Clone of the 1st image ] */
Initially, the container is positioned with left: -100px, allowing the first image to be displayed. To switch between images, apply a JavaScript animation to the CSS property you originally selected.
The accompanying fiddle demonstrates this effect. Below is the basic JavaScript/jQuery code used:
$(function() { var gallery = $('#gallery ul'), items = gallery.find('li'), len = items.length, current = 1, /* the item we're currently looking */ first = items.filter(':first'), last = items.filter(':last'), triggers = $('button'); /* 1. Cloning first and last item */ first.before(last.clone(true)); last.after(first.clone(true)); /* 2. Set button handlers */ triggers.on('click', function() { var cycle, delta; if (gallery.is(':not(:animated)')) { cycle = false; delta = (this.id === "prev")? -1 : 1; /* in the example buttons have id "prev" or "next" */ gallery.animate({ left: "+=" + (-100 * delta) }, function() { current += delta; /** * we're cycling the slider when the the value of "current" * variable (after increment/decrement) is 0 or when it exceeds * the initial gallery length */ cycle = (current === 0 || current > len); if (cycle) { /* we switched from image 1 to 4-cloned or from image 4 to 1-cloned */ current = (current === 0)? len : 1; gallery.css({left: -100 * current }); } }); } }); });
This solution is relatively straightforward and efficient, requiring only two additional DOM insertion operations and simple loop management logic compared to a non-looping slider.
While alternative approaches may exist, this method provides a practical and effective solution for creating an infinity loop slider.
The above is the detailed content of How can I create an infinite image loop slider using JavaScript/jQuery?. For more information, please follow other related articles on the PHP Chinese website!