I have built an infinite carousel which works on on the following concept.when initialised in this example, it clones the 3rd element to the first position and removes the original 3rd element.
This is working as expected, however if “clone of element 3” gets cloned again as the user continuously clicks on the scoller buttons, even with clone(true), it seems to lose all events attached to any of “clone of element 3” descendants.
dimension variable is equal to the list item’s width.
first snippet does the initialising by cloning the last element and prepending it so that it becomes first in the list.
function horizontal_scroll(dimension) {
/* The below 3 lines will set the list of banners up so the
last banner is first, and the list starts at the second position (-980px)
e.g.
On load, the list is like:
{[1]} [2] [3] [4] - marginLeft = 0, so [1] is in the visible area
But after the below 3 lines, the list is like:
[4] {[1]} [2] [3] - marginLeft = -980, so [1] is in the visible area*/
list_holder.addClass("horizontal");
var indent = parseInt(list_holder.css('left')) - dimension;
var lastLi = list_holder.find("li.list:last");
list_holder.prepend(lastLi.clone(true)).css("marginLeft", -dimension);
//... clone it and add it to the beginning of the list.
reset the position of the list so that the original first image is visible
lastLi.remove(); // remove the last LI
}
second snippet manipulates the items depending on whether the user has clicked the left or the right arrow
the arrow variable is used to determine the direction i.e left or right.
this is extracted from its class attribute e.g
function scrollElements(arrow) {
if (direction === "right") { // if it's the right arrow...
animateBy = -(item_dimension * 2); //... animate by double the negative width of the banners to bring the banner in the 3rd position into view
} else {
animateBy = 0; // if it's the left arrow, animate to 0, which will bring the banner in the first position into view
}
arrow.data("active", true);
$(list_holder).animate({
"marginLeft": animateBy
}, 1000, function () { // animate the UL by the set amount, and after it's finished animating...
//list_holder.css({"marginLeft":animateBy}); // animate the UL by the set amount, and after it's finished animating...
if (direction === "right") { //... if it's the right arrow...
var firstLi = list_holder.find("li.list:first"); //... find the first LI in the list...
list_holder.append(firstLi.clone(true)); //... clone it and add it to the end of the list
firstLi.remove(); // remove the first LI
} else { //... if it's the left arrow...
var lastLi = list_holder.find("li.list:last"); //... find the last LI in the list...
list_holder.prepend(lastLi.clone(true)); //... clone it and add it to the beginning of the list
lastLi.remove(); // remove the last LI
}
list_holder.css("marginLeft", -item_dimension); // reset the position of the list so that the original first image is visible
arrow.data("active", false);
});
}