DominikAngerer
DominikAngerer

Reputation: 6530

Scrolling to the bottom of a div which get opened via jquery toggle

I try to scroll to the bottom of a Div which get opened via jquery toggle.

I tried it like this:

    $(document).ready(
    function() {
        $(".menuitem").click(function() {
            $('#'+$(this).attr("id")+'sub').toggle(1000);
            $('html, body').animate({"scrollTop": $('#'+$(this).attr("id")+'sub').offset().top}, 'fast');
    }
);

With the code after scrollTop: $('#'+$(this).attr("id")+'sub') i get the right id of the div which got expanded from the toggle.

The Problem: I'm on the top of the div and not on the bottom so the user can't see the content - only the first line. I somehow have to add the final size of the div to the scroll but how?

Upvotes: 1

Views: 708

Answers (1)

Yussuf S
Yussuf S

Reputation: 2112

Get the height of the element and add it to the scroll

 $('#'+$(this).attr("id")+'sub').offset().top 
 + $('#'+$(this).attr("id")+'sub').height()

however you need to do this after your element has been displayed otherwise it won't get the correct height so add it to the toggle callback like so:

$(".menuitem").click(function() {
    $('#'+$(this).attr("id")+'sub').toggle(1000, function() {
        $('html, body').animate({
            "scrollTop": $('#'+$(this).attr("id")+'sub').offset().top
                       + $('#'+$(this).attr("id")+'sub').height()
        }, 'fast')
    });
}

Upvotes: 1

Related Questions