darkhorse
darkhorse

Reputation: 8722

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

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.

Upvotes: 0

Views: 867

Answers (3)

Mike Irving
Mike Irving

Reputation: 1628

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>

Upvotes: 1

Sourabh Semalty
Sourabh Semalty

Reputation: 90

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

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

Upvotes: 1

Marek Lisiecki
Marek Lisiecki

Reputation: 726

try this one:

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

Upvotes: 2

Related Questions