anthonyCam
anthonyCam

Reputation: 360

Auto-Scroll div horizontally to the very end with overflow-y set to scroll (jQuery)

I am using this jQuery script that automatically scrolls a div horizontally based on the width of the div. But I need it to scroll to the very end of the div based on the end of the content that is inside of the div. The div has an 'overflow-y: scroll' attribute, so I'd like it to scroll through all of the content until it reaches the end.

This is the script I'm currently using:

function animatethis(targetElement, speed) {
    var width = $(targetElement).width();
    $(targetElement).animate({ marginLeft: "-="+width},
    {
        duration: speed,
        complete: function ()
        {
            targetElement.animate({ marginLeft: "+="+width },
            {
                duration: speed,
                complete: function ()
                {
                    animatethis(targetElement, speed);
                }
            });
        }
    });
};
animatethis($('#q1'), 5000);

It does scroll, but it's not scrolling to the very end of the content inside of the div. Here is a jFiddle that shows what I mean: http://jsfiddle.net/rKu6Y/535/

How can I get it to auto-scroll horizontally to the END of the content rather than just the width of the div?

I hope this all makes sense. Thanks.

Upvotes: 1

Views: 10685

Answers (1)

Martin Parenteau
Martin Parenteau

Reputation: 73741

You can animate the scrollLeft property, using scrollWidth and clientWidth:

function animatethis(targetElement, speed) {
    var scrollWidth = $(targetElement).get(0).scrollWidth;
    var clientWidth = $(targetElement).get(0).clientWidth;
    $(targetElement).animate({ scrollLeft: scrollWidth - clientWidth },
    {
        duration: speed,
        complete: function () {
            targetElement.animate({ scrollLeft: 0 },
            {
                duration: speed,
                complete: function () {
                    animatethis(targetElement, speed);
                }
            });
        }
    });
};
animatethis($('#q1'), 5000);

The result can be seen in this jsfiddle.

Upvotes: 8

Related Questions