Explore how to interact with scrolling, react to scrolling events and limit them
Scrolling the page to see the content below the fold is probably the most common event on the page, not a click or keyboard event.
You can listenscroll
Events onwindow
Object to get information every time the user scrolls the page:
window.addEventListener('scroll', event => {
// scroll event detected
})
Inside the event handler, you can checkwindow
propertywindow.scrollY
And usewindow.scrollX
.
window.addEventListener('scroll', event => {
console.log(window.scrollY)
console.log(window.scrollX)
})
please rememberscroll
Events are not a one-off event.
It triggers many times during the scrolling process, not just at the end or the beginning of the scrolling, so if you need to perform any kind of operation, there will be problems.
You should not do any calculations or operations directly in the handler event handler, but we should useThrottlinginstead.
Throttling
Thisscroll
Each event will not trigger the event once, but will continue to call the event processing function during the entire operation.
This is because it provides coordinates so you can keep track of what is happening.
If you perform complex operations in the event handler, it will affect performance and bring a slow experience to site users.
Library that provides throttling functionRodasImplement it with more than 100 lines of code to handle all possible use cases. This is a simple and easy to understand implementation, it usessetTimeoutCache scroll events every 100 milliseconds:
let cached = null
window.addEventListener('scroll', event => {
if (!cached) {
setTimeout(() => {
//you can access the original event at `cached`
cached = null
}, 100)
}
cached = event
})
Throttling also applies to
mousemove
Events seen in the mouse event course. The same thing-moving the mouse will trigger the event multiple times.
This is an example on Codepen:
Look at the penScroll eventBy Flavio Copes (@flaviocopes) InCipher pen.
Tech Wiki Online!