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 particul
Solution 1:
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.
Solution 2:
Consider the following snippet:
$('#myDiv').bind('click',function(){
var pos = $(this).offset().top,
scrollSpeed = 2;
for (var i = pos; i > 0; i=i-scrollSpeed) {
$(window).scrollTop(i);
}
});
It scrolling was binded to #myDiv element on click just for example. Code determines a position of #myDiv element, than calculates number of scroll steps (speed/smoothness). Than does jQuery .scrollTop() thing.
Post a Comment for "Scroll To An Html Element With A Particular Id In Javascript Or Jquery"