Home > Blockchain >  How to scroll to a position after the DOM is loaded using JavaScript?
How to scroll to a position after the DOM is loaded using JavaScript?

Time:02-20

I'm trying the following code:

document.addEventListener("DOMContentLoaded", function() {
    window.scrollTo(0, 100);
});

Unfortunately, it seems like the scroll is being ignored by the browsers, ie, the browser sets whatever position that was there before the reload. Any help is appreciated.

CodePudding user response:

try this one:

window.addEventListener('load', () => {
    setTimeout(() => {
        window.scrollTo(0, 100);
    }, 300);
});

CodePudding user response:

Show the full code. Its working for me, you should check with another browser.

CodePudding user response:

Here you can add 0 sec timing don't need to wait longer

document.addEventListener("DOMContentLoaded", function() {
    setTimeout(function() {window.scrollTo(0, 100);}, 0);
});

CodePudding user response:

Give this a try.

document.addEventListener("DOMContentLoaded", function(){
  setTimeout(function() {
    window.scrollTo(0, 100);
  }, 1000);
});
body {
  width: 100vw;
  height: 200vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-image: linear-gradient(to bottom right, red, yellow);
}
<body>
  <h1>Hello World </h1>
</body>

  • Related