Animate scrollTop with offset

Graeme picture Graeme · Apr 3, 2013 · Viewed 27.1k times · Source

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

Answer

Kaloyan picture Kaloyan · Apr 3, 2013

Use

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

instead of

$(window).scrollTop(theOffset.top - 50);