Animate scrollTop with offset
Asked Answered
H

2

7

I am using jQuery UI accordion but some of the text is too long which causes it to be neaer the top of the page. What i wanted was when a section was opened it would jump to the top of the section. This code works perfectly in doing that but it snaps to the top, which looks clitchy.

$('#accordion').bind('click',function(){
theOffset = $(this).offset();
$(window).scrollTop(theOffset.top - 50);
});

How would i animate the scrollTop so it "glides" to the top

Many thanks

Hydromechanics answered 3/4, 2013 at 10:1 Comment(0)
W
18

Use

$('body,html').animate({
    scrollTop: theOffset.top - 50
});

instead of

$(window).scrollTop(theOffset.top - 50);
Westbound answered 3/4, 2013 at 10:2 Comment(2)
Glad I could help. Please accept this answer by clicking the check to the left if it helped you. Thanks. :)Westbound
quite fast answered +1 from my side.Heartland
P
0

use jquery animate to animate the properties over specified time instead of just applying them instantly.

$('#accordion').bind('click',function(){
    theOffset = $(this).offset();
    $('body,html').animate({
        scrollTop: theOffset.top - 50;
    });
});
Picardi answered 3/4, 2013 at 10:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.