Scrolling a page to see the content below the fold is probably the most common event happening on a page, more than clicks or keyboard events.
You can listen for the scroll
event on the window
object to get information every time the user scrolls the page:
window.addEventListener('scroll', event => {
// scroll event detected
})
Inside the event handler you can check the current vertical scrolling position by checking the window
property window.scrollY
, and the horizontal scolling using window.scrollX
.
window.addEventListener('scroll', event => {
console.log(window.scrollY)
console.log(window.scrollX)
})
Keep in mind that scroll
event is not a one-time thing.
It fires a lot of times during scrolling, not just at the end or beginning of the scrolling, so there’s a problem if you need to do any kind of operation.
You shouldn’t do any computation or manipulation in the handler event handler directly, but we should use throttling instead.
Throttling
The scroll
event is not fired one-time per event, but rather they continuously call their event handler function during all the duration of the action.
This is because it provide coordinates so you can track what’s happening.
If you perform a complex operation in the event handler, you will affect the performance and cause a sluggish experience to your site users.
Libraries that provide throttling like Lodash implement it in 100+ lines of code, to handle every possible use case. A simple and easy to understand implementation is this, which uses setTimeout to cache the scroll event every 100ms:
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 the
mousemove
event we saw in the mouse events lesson. Same thing - that event is fired multiple times as you move the mouse.
Here’s an example on Codepen:
See the Pen Scrolling Events by Flavio Copes (@flaviocopes) on CodePen.
How to get the scroll position of an element
When you are building a user interface in the browser, you might have an element which can be scrolled, and it’s a common need to know the horizontal and vertical scrolling it currently has.
How can you do that?
Once you have the element, you can inspect its scrollLeft
and scrollTop
properties.
The 0, 0
position is always found in the top left corner, so any scrolling is relative to that.
Example:
const container = document.querySelector('. container')
container.scrollTop
container.scrollLeft
Those properties are read/write, so you can also set the scroll position:
const container = document.querySelector('. container')
container.scrollTop = 1000
container.scrollLeft = 1000
Download my free JavaScript Beginner's Handbook
More browser tutorials:
- Some useful tricks available in HTML5
- How I made a CMS-based website work offline
- The Complete Guide to Progressive Web Apps
- The Fetch API
- The Push API Guide
- The Channel Messaging API
- Service Workers Tutorial
- The Cache API Guide
- The Notification API Guide
- Dive into IndexedDB
- The Selectors API: querySelector and querySelectorAll
- Efficiently load JavaScript with defer and async
- The Document Object Model (DOM)
- The Web Storage API: local storage and session storage
- Learn how HTTP Cookies work
- The History API
- The WebP Image Format
- XMLHttpRequest (XHR)
- An in-depth SVG tutorial
- What are Data URLs
- Roadmap to learn the Web Platform
- CORS, Cross-Origin Resource Sharing
- Web Workers
- The requestAnimationFrame() guide
- What is the Doctype
- Working with the DevTools Console and the Console API
- The Speech Synthesis API
- How to wait for the DOM ready event in plain JavaScript
- How to add a class to a DOM element
- How to loop over DOM elements from querySelectorAll
- How to remove a class from a DOM element
- How to check if a DOM element has a class
- How to change a DOM node value
- How to add a click event to a list of DOM elements returned from querySelectorAll
- WebRTC, the Real Time Web API
- How to get the scroll position of an element in JavaScript
- How to replace a DOM element
- How to only accept images in an input file field
- Why use a preview version of a browser?
- The Blob Object
- The File Object
- The FileReader Object
- The FileList Object
- ArrayBuffer
- ArrayBufferView
- The URL Object
- Typed Arrays
- The DataView Object
- The BroadcastChannel API
- The Streams API
- The FormData Object
- The Navigator Object
- How to use the Geolocation API
- How to use getUserMedia()
- How to use the Drag and Drop API
- How to work with scrolling on Web Pages
- Handling forms in JavaScript
- Keyboard events
- Mouse events
- Touch events
- How to remove all children from a DOM element
- How to create an HTML attribute using vanilla Javascript
- How to check if a checkbox is checked using JavaScript?
- How to copy to the clipboard using JavaScript
- How to disable a button using JavaScript
- How to make a page editable in the browser
- How to get query string values in JavaScript with URLSearchParams
- How to remove all CSS from a page at once
- How to use insertAdjacentHTML
- Safari, warn before quitting
- How to add an image to the DOM using JavaScript
- How to reset a form
- How to use Google Fonts