I am designing a simple scrolling page. It is divided into a number of div(or sections). Pressing down or up arrowkey should scrollintoview to next or previous section.
The following code seems to work if I press down or up key once every second, but if I keep pressing down the key, it moves to the next section, but it's stuck in the midway. It's funny, because if I change the scrollintoview parameter into {behavior: "auto"}, it has no such problem.
Is there a way to fix this?
moveToSection(sectionID, sectionY) {
document
.getElementById(sectionID)
.scrollIntoView({ block: "start", behavior: "smooth" });
this.setState({ lastScrollTop: sectionY });
}
checkDownCondition() {
if (this.state.keyDown) {
console.log("key is pressed - returning");
return;
}
this.setKeyDown();
document.removeEventListener("keydown", this.handleKeyDown);
var currentPos = this.state.lastScrollTop;
const sectionTwoY = this.state.sectionTwoY;
const sectionThreeY = this.state.sectionThreeY;
const sectionFourY = this.state.sectionFourY;
const sectionFiveY = this.state.sectionFiveY;
if (this.state.keyDown) {
setTimeout(() => {
// scrolling from section1 to section2
if (currentPos < sectionTwoY) {
this.moveToSection("section2", sectionTwoY);
// scrolling from section2 to section3
} else if (currentPos >= sectionTwoY && currentPos < sectionThreeY) {
this.moveToSection("section3", sectionThreeY);
// scrolling from section3 to section4
} else if (currentPos >= sectionThreeY && currentPos < sectionFourY) {
this.moveToSection("section4", sectionFourY);
// scrolling from section4 to section5
} else if (currentPos >= sectionFourY && currentPos < sectionFiveY) {
this.moveToSection("section5", sectionFiveY);
}
}, 1);
setTimeout(() => {
this.setKeyUp();
document.addEventListener("keydown", this.handleKeyDown);
}, 1000);
}
}