I have a quick fiddle set up here. What I want is to be able to infinitely scroll to the left or right (carousel style) and just have the elements repeat (ie 'fall off' the right edge and re-appear on the left and vice versa). I'm able to capture where I am in the scroll but not sure what the best way to proceed after that is. It seems to me there is a very simple trick that is out there before I go down the route of trying to dynamically move elements.
CSS
#main {
overflow-x:scroll;
overflow-y:hidden;
white-space:nowrap;
}
HTML
<div id="main">
<img src="http://dummyimage.com/150x100/aaa/00f">
<img src="http://dummyimage.com/150x100/000/fff">
<img src="http://dummyimage.com/150x100/000/fff">
<img src="http://dummyimage.com/150x100/000/fff">
<img src="http://dummyimage.com/150x100/000/fff">
<img src="http://dummyimage.com/150x100/000/fff">
<img src="http://dummyimage.com/150x100/000/fff">
<img src="http://dummyimage.com/150x100/000/fff">
<img src="http://dummyimage.com/150x100/000/fff">
<img src="http://dummyimage.com/150x100/ccc/f00">
</div>
JS
$('#main').scroll(function (event) {
var width = $(this)[0].scrollWidth - $(this).width();
console.log('location: ' + $(this).scrollLeft() + ' out of ' + width);
});
This works reasonably well, scrollbar and all:
$('#main').scroll(function (event) {
var factor = this.scrollLeft / (this.scrollWidth - $(this).width());
if(factor < 0.2) {
var move = $(this.lastChild);
move.remove();
$(this).prepend(move);
this.scrollLeft += move.width();
} else if(factor > 0.8) {
var move = $(this.firstChild);
move.remove();
$(this).append(move);
this.scrollLeft -= move.width();
}
});
jsFiddle: http://jsfiddle.net/ZgEZN/10/
Scrolling to the leftmost or rightmost 20% of the scrollbar causes the scrollbar to behave funny, but not drastically glitchy. (Dragging the scrollbar to that area causes the carousel to spin rapidly until the scrollbar is either released or moved somewhere more reasonable. Scrolling to that area in some other way causes the scrollbar to jump back toward the middle.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With