Home > database >  I can't refresh page to top using JavaScript
I can't refresh page to top using JavaScript

Time:01-29

I used this code but it didn't work, I need some help about how to refresh page to top when it loads.

window.addEventListener('load', function(){
   window.scrollTo(0,0)
})

window.onload = (event) => {
   window.scrollTo(0,0)
};

CodePudding user response:

Your code works if the page is loading not at top

For example on a back button or if the page is loaded with an ID in the hash

You CAN just remove the onl oad and have the script inline at the bottom of the page

window.addEventListener('load', function(){
   window.scrollTo(0,0)
})
div { height: 500px; background-color: yellow; }
<div>Div 1</div>
<div>Div</div>
<div>Div</div>
<div>Div</div>
<div>Div</div>
<div>Div</div>
<div>Div</div>
<div>Div</div>
<div>Div</div>
<div>Div</div>
<div>Div</div>
<div>Div</div>
<div>Div</div>
<div>Div</div>
<div>Div</div>
<div>Div</div>
<div>Div</div>
<div id="x">Last Div</div>
<script>
 // mocking the page loading not at top, this is not part of the answer
 document.getElementById("x").scrollIntoView(); //while loading
 
 // put the window.scrollTo(0,0) here if you have issues
 
</script>

CodePudding user response:

Instead of using window.scrollTo(0,0) can you try using document.body.scrollTop = document.documentElement.scrollTop = 0;

Your code should become

window.addEventListener('load', function(){
    document.body.scrollTop = document.documentElement.scrollTop = 0;
})

window.onload = (event) => {
   document.body.scrollTop = document.documentElement.scrollTop = 0;
};
  •  Tags:  
  • Related