Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll to an html element with a particular id in javascript or jquery

I have html elements with id's assigned. Now I want to scroll to those elements. I see jQuery has a scrollTop which takes an integer value.. How do I easily just make a particular html element with an id scroll to the top? Ideally, with nice and smooth animation.

A quick search showed many scrolling plugins... if a plugin is needed for the above functionality, what's the most popular one? I'm also using jquery-ui.

like image 336
at. Avatar asked Dec 28 '22 15:12

at.


1 Answers

You could use something like this to scroll to #someElement when the page loads:

$(document).ready(function() {
    $("html, body").animate({scrollTop: $("#someElement").offset().top}, 1000); 
});

It simply animates the scrollTop property of the body element, and uses the top offset of some specific element as the position to scroll to. The animation lasts for 1000ms.

Note: it selects both html and body so it works across browsers. I'm not sure on the specifics, but some quick tests show that Chrome uses body, but Firefox and IE use html.

Here's a working example.

like image 156
James Allardice Avatar answered Jan 14 '23 05:01

James Allardice