Reputation: 523
I've got a problem with a script that fires 2 times and it clone some columns and append twice.
My goal is to clone the element, which is not in the viewport, and append it at the end, then delete the element from front.
It seems like the element goes of the viewport and enter twice in the condition, where I check if left of the element is greater than its width.
That means I got two clone of the same element and appended twice at the end, which is not good.
Strange thing is that the delete of the element fire once.
here's some code:
var moving = false,
$holder = $('#carousel');
$holder.on('transitionend', function (){
moving = false; // era true
});
offset = 600;
function getPosition() {
wrapper = document.getElementById('carousel');
wrapper_length = wrapper.childElementCount;
width_of_elements = wrapper.children[0].getBoundingClientRect().width;
current_left = wrapper.children[0].getBoundingClientRect().left;
positive_current_left = current_left * -1;
if(Math.round(positive_current_left) > Math.round(width_of_elements)){
// clone + set left after the last one
clone = wrapper.children[0].cloneNode(true);
clone.style.left = wrapper.children[wrapper_length - 1].getBoundingClientRect().left + (offset * 2.6) + "px";
console.log(clone);
// append child cloned
wrapper.appendChild(clone);
// delete element cloned
wrapper.removeChild(wrapper.childNodes[0]);
}
if (!moving) {
window.requestAnimationFrame(getPosition);
}
}
window.requestAnimationFrame(getPosition);
Am I wrong somewhere?
here's a fiddle to see it in action:
Upvotes: 0
Views: 360
Reputation: 705
If all you want to do is to move an element to the end, you can "re"-appendChild. Looks a bit wonky when it starts to come around, but that you can fix. ;)
if (Math.round(positive_current_left) > Math.round(width_of_elements)) {
// clone + set left after the last one
moveMe = wrapper.children[0];
moveMe.style.left = wrapper.children[wrapper_length - 1].getBoundingClientRect().left + (offset * 2.6) + "px";
// append child cloned
wrapper.appendChild(moveMe);
}
Upvotes: 1