Briefly
scroll
is an event that occurs when a user scrolls the page or element in any plane. Methods of scrolling can include: mouse wheel, keyboard buttons, scroll bars on the screen.
How to write
document.addEventListener('scroll', function(event) { console.log(event)})
document.addEventListener('scroll', function(event) { console.log(event) })
How to understand
The scroll
event occurs only during scrolling. Try scrolling the text in the demo below:
scroll
uses the basic event element, which lacks information about the speed of scrolling and direction.
To understand how far the page or element has scrolled, you can get that element from the DOM tree or the keyword this
and request the scroll
or scroll
properties.
document.addEventListener('scroll', function() { // Get the height of the element, // on which the event occurred console.log(this.scrollTop)})
document.addEventListener('scroll', function() { // Get the height of the element, // on which the event occurred console.log(this.scrollTop) })
In practice
Advice 1
🛠 If you subscribed to scroll
, be prepared to receive a large amount of events. The event will come approximately on every frame. Therefore, it is not recommended to perform heavy computations and DOM modifications in the handler. This will lead to frame loss during rendering and the feeling that the site is lagging.
🛠 You can avoid a large number of scroll
events by using a technique called throttling. Its essence is to accept the next event only after a certain interval of time has passed.
const throttle = (func, limit) => { let lastFunc let lastRan return function() { const context = this const args = arguments if (!lastRan) { func.apply(context, args) lastRan = Date.now() } else { clearTimeout(lastFunc) lastFunc = setTimeout(function() { if ((Date.now() - lastRan) >= limit) { func.apply(context, args) lastRan = Date.now() } }, limit - (Date.now() - lastRan)) } }}// The code will be triggered once every seconddocument.addEventListener('scroll', throttle(function() { return console.log('Hey! It is', new Date().toUTCString())}, 1000))
const throttle = (func, limit) => { let lastFunc let lastRan return function() { const context = this const args = arguments if (!lastRan) { func.apply(context, args) lastRan = Date.now() } else { clearTimeout(lastFunc) lastFunc = setTimeout(function() { if ((Date.now() - lastRan) >= limit) { func.apply(context, args) lastRan = Date.now() } }, limit - (Date.now() - lastRan)) } } } // The code will be triggered once every second document.addEventListener('scroll', throttle(function() { return console.log('Hey! It is', new Date().toUTCString()) }, 1000))