jqueryjquery-animatescrolltop

scrolling to the parent div top with jquery


I thought this would be easy.

I have the following HTML

<div>
<div id="child"></div>
</div>

I tried a couple things

if ($('#child').length){
    $('html, body').animate({scrollTop: $(this).parent().offset().top}, 'slow');
}

and

if ($('.success_div').length){
    pdiv = $(this).parent();
    $('html, body').animate({scrollTop: pdiv.offset().top}, 'slow');
}

error: TypeError: pdiv.offset(...) is undefined


Solution

  • How about this?

    if ($('#child').length){
        $('body').animate({scrollTop: $('#child').parent().offset().top},'slow');
    });
    

    calling an element in an if statement doesn't select it, so $(this) matches nothing inside of if ($('#child').length){, so i called $('#child') again inside of the statement.