Home > Article > Web Front-end > How to Achieve a Seamless Infinity Loop Image Slider Using JavaScript/jQuery?
Infinity Loop Slider Design Concepts Using JavaScript/jQuery
To create an infinity loop image slider with optimal code readability, maintainability, and reusability, consider the following blueprint:
Image Arrangement for Infinity Loop Effect
To achieve the illusion of an infinite loop, implement one of two approaches:
Cloning Images for Seamless Looping
To create an infinite loop, clone the first and last images in the sequence. Then, while scrolling:
Example Code
Consider the following JavaScript/jQuery code snippet as an example implementation:
$(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 }); } }); } }); });
The above is the detailed content of How to Achieve a Seamless Infinity Loop Image Slider Using JavaScript/jQuery?. For more information, please follow other related articles on the PHP Chinese website!