📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials jQuery in Practice Scroll Events

Scroll Events

5 min read Quiz at the end
Listen to scroll events with $(window).on('scroll', fn). Use scrollTop() to read position and toggle classes for sticky navbars. Always debounce the scroll handler to avoid performance problems from rapid firing.

Scroll Handling

$(window).on('scroll', function() {
  const top = $(this).scrollTop();
  if (top > 100) {
    $('#navbar').addClass('sticky');
  } else {
    $('#navbar').removeClass('sticky');
  }
});

// Smooth scroll to element
$('a[href^="#"]').on('click', function(e) {
  e.preventDefault();
  $($(this).attr('href'))[0].scrollIntoView({ behavior: 'smooth' });
});
Topic Quiz · 5 questions

Test your understanding before moving on

1. Which method gets the scroll position?
💡 .scrollTop() returns or sets the vertical scroll position.
2. How do you run code on scroll?
💡 $(window).on('scroll', fn) attaches a scroll event handler.
3. Why debounce scroll handlers?
💡 Scroll fires dozens of times per second — debouncing prevents performance issues.
4. Which method gets element's offset from document top?
💡 .offset().top returns the element's distance from the top of the document.
5. How do you smoothly scroll to an element?
💡 el.scrollIntoView({behavior:'smooth'}) performs a smooth scroll to the element.