0

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.

Paul Z.
  • 855
  • 1
  • 10
  • 27
  • Does this answer your question? [Cross browser JavaScript (not jQuery...) scroll to top animation](https://stackoverflow.com/questions/8917921/cross-browser-javascript-not-jquery-scroll-to-top-animation) – Yogi Oct 14 '22 at 04:50
  • @Yogi This article provides an alternate way to scroll, but scroll behavior is not that wide compatible for multiple browsers. – Paul Z. Oct 14 '22 at 15:03
  • The other question, including the code, is identical to this question. So you may want to add more detail to your question to explain how it is different. Without more detail this question could be closed as a duplicate. [scrollTo smooth](https://caniuse.com/?search=scrollTo) is supported by all modern browsers. So if the question applies to browsers older than 2018 then please include that too. – Yogi Oct 14 '22 at 15:24

3 Answers3

0

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;
}
Libertas
  • 358
  • 2
  • 5
  • 11
0

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

scrollTo() is supported in all browsers.

David
  • 1
0

There are two other questions that may help you:

How to page scrolling like this?

Scroll to a specific position on a page using Javascript / Jquery

and I think these links may help you:

https://www.codespeedy.com/scroll-to-a-specific-position-in-javascript/

https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-behavior

https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

.scrollTo

scroll-behavior

scrollIntoView() scrollIntoView(alignToTop) scrollIntoView(scrollIntoViewOptions)

You better read all articles.

Behrad Hajmiri
  • 230
  • 2
  • 7