'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.



Solution 1:[1]

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

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

Solution 2:[2]

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>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sourabh Semalty
Solution 2 David Yappeter