Reputation: 625
So I'm trying to scroll to the top of the screen when the user submits a form. The answers on stacked overflow don't seem to work for me.
here's my code:
handleClick (evt) {
evt.preventDefault();
this.calculateScore();
this.setState({submittingQuiz: true});
// let myPage = document.querySelector('body');
// myPage.scrollTo(0,0); Couldn't get this way to work either
window.scrollTo({top: 0, behavior: 'smooth'})
}
Any thoughts on how to fix this problem. I have some styling I think may be messing with it..
html {
background-image: url('./tupac.jpeg');
background-position-y: -580px;
background-repeat: no-repeat;
background-size: cover;
overflow: hidden;
}
Anyone got a clue?
Upvotes: 3
Views: 9457
Reputation: 31
If you have something like height: 100vh
in the parent it won't work, but you can use this approach.
const container = document.getElementById('container');
if (container) {
container.scrollIntoView({ block: 'start', behavior: 'smooth' });
}
You can give a container <div style={{ position: 'absoulte', top: '-10px' }} />
-10px
if you need to go all the way to top, you give negative margin, to position div at the top (or where you want to scroll), and you are ready to go.
also see scrollIntoView
Upvotes: 1
Reputation: 145
I had similiar issue trying to use window.scrollTo(0, 0)
inside useEffect
. No height: 100vh
in my code.
setTimeout(() => {
window.scrollTo(0, 0);
});
did the trick, no actual timeout needed in my case.
Upvotes: 1
Reputation: 31
I also had this issue and, as the marked solution mentions, removing height: 100vh
solved the issue for me. However, my website was not functioning properly without height: 100vh
(elements would reach the very bottom of the page even with sufficient margin/padding).
If you need height: 100vh
, then I would recommend using element.scrollIntoView()
, instead of window.scrollTo()
, with the element being some element near or at the top of your website.
Upvotes: 3
Reputation: 776
This probably happens because the body
has a height: 100vh;
or some main container of the application has the same height: 100vh;
Try remove height: 100vh;
on body
and the main container of the application and test it again.
Upvotes: 3