jQuery scroll to element
Assuming you have a button with the id button
, try this example:
$("#button").click(function() {
$([document.documentElement, document.body]).animate({
scrollTop: $("#elementtoScrollToID").offset().top
}, 2000);
});
I got the code from the article Smoothly scroll to an element without a jQuery plugin. And I have tested it on the example below.
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
$(document).ready(function (){
$("#click").click(function (){
$('html, body').animate({
scrollTop: $("#div1").offset().top
}, 2000);
});
});
</script>
<div id="div1" style="height: 1000px; width 100px">
Test
</div>
<br/>
<div id="div2" style="height: 1000px; width 100px">
Test 2
</div>
<button id="click">Click me</button>
</html>
jQuery .scrollTo(): View - Demo, API, Source
I wrote this lightweight plugin to make page/element scrolling much easier. It's flexible where you could pass in a target element or specified value. Perhaps this could be part of jQuery's next official release, what do you think?
Examples Usage:
$('body').scrollTo('#target'); // Scroll screen to target element
$('body').scrollTo(500); // Scroll screen 500 pixels down
$('#scrollable').scrollTo(100); // Scroll individual element 100 pixels down
Options:
scrollTarget: A element, string, or number which indicates desired scroll position.
offsetTop: A number that defines additional spacing above scroll target.
duration: A string or number determining how long the animation will run.
easing: A string indicating which easing function to use for the transition.
complete: A function to call once the animation is complete.
If you are not much interested in the smooth scroll effect and just interested in scrolling to a particular element, you don't require some jQuery function for this. Javascript has got your case covered:
https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView
So all you need to do is: $("selector").get(0).scrollIntoView();
.get(0)
is used because we want to retrieve the JavaScript's DOM element and not the JQuery's DOM element.