Smith Smithy
Smith Smithy

Reputation: 585

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

Upvotes: 2

Views: 7965

Answers (2)

RayJ
RayJ

Reputation: 742

To scroll a child element to the top of a parent element.

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

Upvotes: 0

FiLeVeR10
FiLeVeR10

Reputation: 2165

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.

Upvotes: 3

Related Questions