3

I am trying to have my page snap to the top when the page is reloaded. To do this I am using JavaScript like so:

window.onbeforeunload = function() {
   window.scrollTo(0,0);
}

This was working great for me until I turned on smooth scrolling in my CSS:

scroll-behavior: smooth;

And now it won't work at all.

What I'd like to be able to do is temporarily turn off the CSS smooth scrolling behavior from JS something like this:

window.onbeforeunload = function() {
   document.getElementsByTagName("HTML")[0].style.scrollBehavior = "auto";
   window.scrollTo(0,0);
}

However it looks like style.scrollBehavior isn't valid and I can't find anything that is. Is it possible to change this from JavaScript?

If not is there a way to turn smooth scrolling on and off from within JavaScript that is fairly simple?

I just would like to keep things pretty straight forward if possible.

0

1 Answer 1

5

You can use scrollIntoView with an html element passing smooth as the behaviour, as in:

element.scrollIntoView({ block: 'start',  behavior: 'smooth' });

You can see a working example in How to get the button when clicked go to a certain part of the page?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.