skip to Main Content

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.

3

Answers


  1. 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;
    }
    
    Login or Signup to reply.
  2. You can use window.scrollTo({top: 1000, behavior: "smooth" });
    Scroll smoothly the document to specified coordinates.

    scrollTo() is supported in all browsers.

    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search