Home > database >  Smooth scroll to position with pure Javascript
Smooth scroll to position with pure Javascript

Time:10-14

How to create a pure Javascript function that works exactly like this?

$('html, body').animate({
   scrollTop: y
}, 400);

Here y is a parameter for vertical position to reach. In a site where I'm working now, there is a horizontal nav that is fixed in the top while scrolling and auto focuses corresponding menu item when it scrolls to the mapped section. Also, when the menu item is clicked, body container should auto scroll to that section. I could do this by using jQuery animation easily, but the client doesn't want to use jQuery anymore.

I have researched quite a few questions & answers on this site where window.requestAnimationFrame() or CSS transition effect. But I could not find out a perfect solution.

Thanks.

CodePudding user response:

You can use window.scrollTo() to scroll to specified location or window.scrollBy() to scroll by some number of pixels. Those two functions don't scroll smoothly, for that you need a bit of CSS:

html {
  scroll-behavior: smooth;
}

CodePudding user response:

You can use window.scrollTo({top: 1000, behavior: "smooth" });
Scroll smoothly the document to specified coordinates.

scrollTo() is supported in all browsers.

  • Related