How to Bind Window Scroll Event in jQuery
This article provides a direct guide on how to bind an event handler to the window scroll event using jQuery. You will learn the current standard syntax for attaching the scroll listener, how to capture the current scroll position, and best practices to ensure optimal performance when handling continuous scroll events.
Recommended Syntax:
$(window).on()
The standard and most versatile way to bind a scroll event to the
window in modern jQuery is by using the .on() method.
$(window).on('scroll', function() {
console.log('The window is scrolling.');
});Accessing the Scroll Position
Inside the event callback, you can retrieve the current vertical or
horizontal scroll position using .scrollTop() or
.scrollLeft().
$(window).on('scroll', function() {
let scrollPosition = $(this).scrollTop();
if (scrollPosition > 200) {
console.log('Scrolled past 200 pixels');
}
});Deprecated Shorthand
Syntax: $(window).scroll()
Historically, jQuery offered a .scroll() shortcut
method. While it functions in older versions, it is considered
deprecated in newer releases of jQuery in favor of
.on('scroll', handler).
// Legacy syntax (not recommended for new projects)
$(window).scroll(function() {
console.log('Scrolling with legacy syntax.');
});Performance Consideration
Because the scroll event fires rapidly whenever a user
scrolls, executing heavy DOM manipulations or complex calculations
directly inside the handler can cause UI lag. Use requestAnimationFrame,
throttling, or debouncing to limit the rate at which the callback
executes.
let isScrolling = false;
$(window).on('scroll', function() {
if (!isScrolling) {
window.requestAnimationFrame(function() {
// Place DOM updates or logic here
console.log('Scroll position:', $(window).scrollTop());
isScrolling = false;
});
isScrolling = true;
}
});