Reputation: 580
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.
Upvotes: 3
Views: 1544
Reputation: 18002
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?
Upvotes: 5