jQuery scroll: Main Tips
.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
Theory is great, but we recommend digging deeper!
Usage of jQuery .scroll()
.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:
You will, however, need to specify a few arguments for
.scroll() in jQuery to attach an event handler:
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.