My page has a fullscreen teaser at the top. When the user starts scrolling I want the whole page to scroll down to the following segment automatically and smoothly.
Unfortunately the following code does not work. As posted it does not scroll at all and when I don't set the scrolling variable to true to avoid multiple scrollIntoView executions it's super slow.
What's a good way to fix this using vanilla JS?
Example, tested in Chrome:
let scrolling = false;
window.onscroll = () => {
const offset = window.pageYOffset;
if (offset > 0 && offset < window.innerWidth && !scrolling) {
scrolling = true;
document.querySelector('.somecontent').scrollIntoView({behavior:'smooth'});
}
if (offset >= window.innerWidth) {
scrolling = false;
}
}
.someteaser {
background: blue;
height: 100vh;
width: 100vw;
}
.somecontent {
background: red;
height: 200vh;
width: 100vw;
}
<div class="someteaser"></div>
<div class="somecontent"></div>
// Update
So the problem is the behavior:'smooth' option. Without it the scrolling works, but of course isn't smooth anymore. This seems to be a bug on scorllIntoView which I don't really understand. My temporary solution uses this script, which works alright: https://github.com/cferdinandi/smooth-scroll