🚨 Time is Running Out: Reserve Your Spot in the Lucky Draw & Claim Rewards! START NOW

Code has been added to clipboard!

jQuery .scroll(): Assigning a Handler for a scroll Event

Reading time 2 min
Published Jan 10, 2018
Updated Oct 17, 2019

jQuery scroll: Main Tips

  • The .scroll() jQuery method is closely related to the scroll event.
  • In its simplest form, it can trigger said event.
  • By adding arguments, you can also make jQuery .scroll() attach an event handler to the scroll event.
  • To detach the handler, use .off() with the event parameter defined as scroll.
DataCamp
Pros
  • Easy to use with a learn-by-doing approach
  • Offers quality content
  • Gamified in-browser coding experience
  • The price matches the quality
  • Suitable for learners ranging from beginner to advanced
Main Features
  • Free certificates of completion
  • Focused on data science skills
  • Flexible learning timetable
Udacity
Pros
  • Simplistic design (no unnecessary information)
  • High-quality courses (even the free ones)
  • Variety of features
Main Features
  • Nanodegree programs
  • Suitable for enterprises
  • Paid Certificates of completion
Udemy
Pros
  • Easy to navigate
  • No technical issues
  • Seems to care about its users
Main Features
  • Huge variety of courses
  • 30-day refund policy
  • Free certificates of completion

Usage of jQuery .scroll()

The jQuery .scroll() method either triggers a scroll event manually, or attaches an event handler that executes a function when one occurs. In the example below, you can see the total number of times you scrolled constantly updated and displayed below the <div> element:

A jQuery scroll event occurs each time a change in the elements scroll position is detected. It can be caused not only by literal scrolling with the scroll wheel on your mouse but also by pressing the arrow keys on your keyboard, as well as clicking or dragging the scroll bar with the cursor of the mouse.

Syntax for jQuery .scroll()

The syntax required to trigger the jQuery scroll event manually is very simple, as there are no arguments you should define:

$("selector").scroll();

You will, however, need to specify a few arguments for .scroll() in jQuery to attach an event handler:

$("selector").scroll(data, callback);

The only required argument is callback: it represents the callback function you wish to set as an event handler. If your function needs some additional data to run, include it in the brackets before the function.

Note: you can use jQuery .scroll() with window objects, scrollable frames, and elements that have their CSS overflow property set to scroll.