Here is my problem, I am searching to set the scroll to top of the page on load but currently Chrome, IE and Firefox reset the scroll position to the same as it was on previous page, so how can I set scroll to top?
It seems that scrollTo is just ignored by those web browsers and I tried many over methods using scrollTo (find on SO) but they all do nothing...
Need help! Thank you all!
Here is my problem, I am searching to set the scroll to top of the page on load but currently Chrome, IE and Firefox reset the scroll position to the same as it was on previous page, so how can I set scroll to top?
It seems that scrollTo is just ignored by those web browsers and I tried many over methods using scrollTo (find on SO) but they all do nothing...
Need help! Thank you all!
Share Improve this question edited Sep 8, 2016 at 12:11 Mukesh Ram 6,3284 gold badges20 silver badges37 bronze badges asked Sep 8, 2016 at 9:22 N.KN.K 1,6902 gold badges22 silver badges32 bronze badges 2- Browser automatically sets the scroller to the top. Some code must be changing it. – Flying Gambit Commented Sep 8, 2016 at 9:28
- I'am sure thats not the case, many people have the same problem and it has been reported as a convenience feature of chrome for exemple he rememeber the last scroll position and automatically set it back on reload/load :3 edit: Thank you anyay :) – N.K Commented Sep 8, 2016 at 9:34
4 Answers
Reset to default 11Okay, in case it can help some of you guys, here is what i'am using right now (i just found it, like 30 seconds after posting the question lmao...) and it seems to work:
window.onbeforeunload = function() {window.scrollTo(0,0);}
Edit: it might be because the browser remembers the last scroll pos, so setting it to top before unload makes, for exemple, chrome remembering 0,0 instead of x,y
You could try somthing like this :
<!DOCTYPE html>
<html>
<body onload="myFunction()">
<script>
function myFunction() {
document.body.scrollTop = document.documentElement.scrollTop = 0;
}
</script>
</body>
</html>
Hope it helps :)
This is our vanilla javascript implementation. It has a simple easing effect so that the user doesn't get shocked after clicking the To Top button.
Its very small and gets even smaller when minified. Devs looking for an alternative to the jquery method but want the same results can try this.
HTML
<button id="to-top">To Top</button>
JS
document.querySelector("#to-top").addEventListener("click", function(){
var toTopInterval = setInterval(function(){
var supportedScrollTop = document.body.scrollTop > 0 ? document.body : document.documentElement;
if (supportedScrollTop.scrollTop > 0) {
supportedScrollTop.scrollTop = supportedScrollTop.scrollTop - 50;
}
if (supportedScrollTop.scrollTop < 1) {
clearInterval(toTopInterval);
}
}, 10);
},false);
you can use $anchorScroll()
and here is a documentation for it angular-js: anchor-Scroll attribute