How to make a window.scrollTo(0.0) without animation

Asked

Viewed 184 times

2

I have an React application that in certain situations (because of the React-router) I should scroll to the top of the page. The problem is that in most cases the scroll should be animated and in some specific cases not.

Is there any way I can force the scroll to the top of the page to happen without any animation?

Note: as in most code one should use the smoth scroll I have this set in the global files of my SCSS:

html {
  scroll-behavior: smooth;
}

2 answers

3


I believe that behavior in the API (scroll(), scrollBy() and scrollTo()) only has 2 possible values, Smooth and auto, so I believe that

Same goes for CSS:

scroll-behavior: auto;
scroll-behavior: smooth;

Apparently the CSS scroll-behavior does not support Safari, different from the API depending on the caniuse, which is only supported in Safari 13.1+ for Macos (i.e., not supported by iOS), so it is best to use the API if the objective is to ACTIVATE, to deactivate is irrelevant if React uses the scroll-behavior: smooth;, since Smooth probably does not occur or if it occurs is some polyfill used (internally, I am not experienced in React).

So by default the auto probably will depend on browser to browser, what you can try is to apply a class like this:

.behavior-auto {
    scroll-behavior: auto !important;
}

And dynamically apply to the element of interest something like:

document.documentElement.classList.toggle('behavior-auto', true)

And to remove:

document.documentElement.classList.toggle('behavior-auto', false)

If you want to disable any "child element" maybe you can try:

.behavior-auto, .behavior-auto * {
    scroll-behavior: auto !important;
}

But like I said, it will depend on browser to browser, although MDN states that the auto value scrolls in a single motion.

  • The compatibility of js Options Object and Behavior css is the same

  • Hello dear @ruansenadev, could you enlighten me where I said it wasn’t? After all I did not comment on compatibility, what I said is that BOTH only have the value as AUTO, and AUTO refers to a default behavior, which may even be user-agent. Understands?

  • I made a comment to complement..

  • 1

    @ruansenadev has a detail for macOS vs iOS Safari, edited response, does not interfere for those who want to "disable", for those who want to "activate" the smooth scrolling would be better then the API instead of CSS.... Of course you have to understand that you have behaviors that are from the operating system and/or some polyfill like https://www.npmjs.com/package/smoothscroll-polyfill

1

Call the function with value of scrollOptions

window.scrollTo({top: 0, left: 0, behavior: 'auto'});

The compatibility of js Options Object and Behavior css is the same

Browser other questions tagged

You are not signed in. Login or sign up in order to post.