How to Create a Scroll to Top of Div Function Using jQuery?

Estimated read time 1 min read

To create a “scroll to top of div” function using jQuery, you can use the animate() function to smoothly scroll the div to the top. Here’s an example function:

function scrollTopOfDiv() {
  $('html, body').animate({
    scrollTop: $('#myDiv').offset().top
  }, 500); // adjust the duration of the animation as needed

In this function, $('html, body').animate() animates both the html and body elements to scroll smoothly to the top of the #myDiv element. The offset().top function gets the top position of the #myDiv element.

You can then call this function when a button or link is clicked, like this:

<button onclick="scrollTopOfDiv()">Scroll to top of div</button>

This will trigger the scrollTopOfDiv() function and smoothly scroll the div to the top.

Note that this example assumes that you have a div with the ID myDiv that you want to scroll to the top of. If you have a different ID for your div, you’ll need to adjust the $('#myDiv') selector in the scrollTop() function accordingly.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply