We can use jQuery to scroll to a div by using the jQuery animate method along with the jQuery offset() method.
$("html, body").animate({ scrollTop: $("#div1").offset().top }, "1000");
Note that the number 1000 above is the speed at which we want the scroll to happen in milliseconds. We can change this number to whatever spend we want to scroll at.
Let’s say we have the following HTML:
This is a div
To scroll to top of the div, #div1, we can use the jQuery animate method combined with the jQuery offset method. We will use the offset method to get the coordinates of the div, and get the top position the div from this method.
$("html, body").animate({ scrollTop: $("#div1").offset().top }, "1000");
If you are using WordPress, don’t forget to change the $ to jQuery as below:
jQuery$("html, body").animate({ scrollTop: $("#div1").offset().top }, "1000");
Using jQuery to Scroll to a Div with a Click
Let’s say we have the following HTML code and we want to scroll smoothly to the div with id #scroll-to-me.
This is the div that we will scroll to on click.
Scroll
We can utilize both the jQuery click() method and jQuery animate() method to scroll to the top of the div.
We will also use the offset() method to get the top position of the div so that we can scroll to it.
Here is the jQuery code:
$("#click-me").click(function() {
$('html, body').animate({ scrollTop: $("#scroll-to-me").offset().top }, '1000');
});
The final code and output for this example of how to scroll to a div using jQuery and Javascript is below.
Code Output:
Full Code:
This is the div that we will scroll to on click.
Scroll
Hopefully this article has been useful for you to understand how to use jQuery to scroll to a div.