Zack Michener
Zack Michener

Reputation: 53

How does one update scrollHeight after appending elements to a div?

I have a div containing several images, with the overflow hidden, which slowly scrolls down. I would like, when the scroll gets to the bottom, to clone the first element and append it to the bottom, so it will continue scrolling.

All this so far I have accomplished, except it doesn't keep scrolling, because the scrollHeight property is still the original value. Is there any way to update the scrollHeight value of the div?

My script so far:

$(document).ready(function() {
$("#carousel").scrollTop(0);
intervalID = setInterval("scrollCarousel()",50);

carousel = document.getElementById("carousel");
});

function scrollCarousel() {


if ( $("#carousel").scrollTop() > $("#carousel:first").height() ||
        $("#carousel").scrollTop() + carousel.offsetHeight >
        carousel.scrollHeight ) {

    elem = $("#carousel").children(':first-child').clone();
    console.debug(elem);
    elem.appendTo($("#carousel"));
    carousel.scrollHeight += elem.height;
}
else {
    $("#carousel").scrollTop( $("#carousel").scrollTop() + 1 );
}
}

Upvotes: 0

Views: 3905

Answers (2)

Paul
Paul

Reputation: 141887

Here you go:

http://jsfiddle.net/Paulpro/bPrY7/

You had a few mistakes:

First of all you shouldn't put a string in setInterval. Especially when you are just calling a function. Since strings get parsed by eval they are quite slow.

Secondly you want to remove the element from the top when you append it to the bottom, and then just adjust the scroll position accordingly.

Also $("#carousel") is a lot slower than $(carousel) when you already have the DOM element.

Upvotes: 1

neslonso
neslonso

Reputation: 1

just an idea, if you can put the first child at the end of the carousel statically, you can avoid the clone and therefore the problem.

Hope this helps. Regards.

Upvotes: 0

Related Questions