When i refresh the page in google chrome, both mobile and pc, the scrollbar doesn't starts on the top, and this causes a visual bug on my page, which should start at the top, because I use overflow: hidden
to hide the scrollbar and only modify the position of the sections, using a scrolling effect.
So, I wanted to know if there is a way to manipulate the scrollbar position in javascript or html, so that it always starts at the top. This only happens in Chrome
CodePudding user response:
Just set document.scrollTop = 0
on page load, This should do the trick.
CodePudding user response:
Sounds like you're looking for Element.scrollTop
const scroller = document.querySelector("#scroller");
const output = document.querySelector("#output");
const button = document.querySelector("#button");
button.addEventListener("click", () => scroller.scrollTop = 0);
scroller.addEventListener("scroll", (event) => {
output.textContent = `scrollTop: ${scroller.scrollTop}`;
});
#scroller {
overflow: scroll;
height: 150px;
width: 150px;
border: 5px dashed orange;
}
#output {
padding: 1rem 0;
}
<button id="button">Scroll to top</button>
<div id="container">
<div id="scroller">
<p>
Far out in the uncharted backwaters of the unfashionable end of the
western spiral arm of the Galaxy lies a small unregarded yellow sun.
Orbiting this at a distance of roughly ninety-two million miles is an
utterly insignificant little blue green planet whose ape-descended life
forms are so amazingly primitive that they still think digital watches are
a pretty neat idea.
</p>
</div>
</div>
<div id="output">scrollTop: 0</div>