I'm working on my first Page Scroller. I do it in a functional way.
It's works with 'wheel' event. Function "scroll" is responsible for recognizing the direction.
I would like to do to the same with 'keydown' event but I get an error
"Uncaught TypeError: Failed to execute 'scroll' on 'Window': cannot convert to dictionary. at HTMLDocument.eval (scroller.js:75)"
//Scroller
const rootElement = document.querySelector('#root')
const sections = [...document.querySelectorAll('section')]
let currentSectionIndex = 0;
let isPaused = false;
document.addEventListener( 'wheel', (e) => {
listenScroll(e)
function listenScroll(e) {
if(isPaused) return;
isPaused = true;
setTimeout(() => {
isPaused = false;
}, 500)
const direction = e.deltaY < 0 ? -1 : 1;
scroll(direction)
}
function scroll(direction) {
if(direction === 1) {
const isLastSection = currentSectionIndex === sections.length - 1;
if(isLastSection) return;
} else if(direction === -1) {
const isFirstSection = currentSectionIndex === 0;
if(isFirstSection) return;
}
currentSectionIndex = currentSectionIndex + direction;
scrollToCurrentSection()
}
function scrollToCurrentSection() {
sections[currentSectionIndex].scrollIntoView({
behavior: "smooth",
block: "start",
})}
})
document.addEventListener('keydown', (e) => {
if(e.keyCode == 40){scroll(1);}
else if(e.keyCode == 38){scroll(-1);}
})
My JavaScript fails. Just only need to take the "scroll" and "scrollToCurrentSection" functions out of the wheel eventListener.