Reputation: 2018
I'm trying to work out a client side solution for an looping image scroll using jQuery. The center div contains 4 images which will move to the right. As the furthest right image leaves the page, it is added to the beginning of the div so it scrolls around again.
I'm not explaining it very well so I made a diagram:
Any help would be appreciated.
Upvotes: 3
Views: 983
Reputation:
I've done this before. The easiest way to go about this is to do:
var nextImage = function() {
$('#container').children().last().insertBefore(
$('#container').children().first();
)
}
Or if you add a class to each image you can do:
var nextImage = function() {
$('img.slider:last').insertBefore($('img.slider:first'));
}
Then set an interval:
window.sliderInterval = setInterval(function(){ nextImage(); }, 500);
Upvotes: 1
Reputation: 2322
Here's a fairly simple proof of concept that I whipped up. It's a little bit unstable (a lot of guesswork with the scroll numbers was involved), but it should be what you're looking for, and it doesn't require any plugins or additional libraries.
function scroller () {
padding = 5;
border = 1;
$(".item").first().insertAfter($(".item").last());
$(".gallery").animate({scrollLeft: $(".item").first().outerWidth() + padding + border, easing: 'swing'}, 1200, function(){
$(".gallery").scrollLeft(1);
scroller();
});
}
http://jsfiddle.net/IronFlare/L8L4e2eg/
EDIT:
I couldn't manage to make the animation completely smooth using jQuery, so I found and modified an existing infinite scroller created solely with CSS using the animation
and keyframes
attributes. Just like my previous example in jQuery, it requires some fine tuning in order to get make it look completely right, but it pays off in the end.
@-webkit-keyframes moveSlideshow {
0% { left: 0; }
100% { left: -635px; }
}
http://jsfiddle.net/IronFlare/hrcekoha/3/
Upvotes: 2
Reputation: 7628
Expanding on my comment above recommending to use the Slick jQuery plugin (http://kenwheeler.github.io/slick/) I've created a fiddle for you. http://jsfiddle.net/4ydy7ooz/
$('.multiple-items').slick({
infinite: true,
slidesToShow: 3,
slidesToScroll: 3
});
Code above so the fiddle is linked.
Upvotes: 0