jQuery Scroll Event

The jQuery scroll event works just the .click() event, the main difference is that we usually want to bind it to the whole document (the webpage) rather than a specific div or img tag.

So the event declaration will look like this:

Note: This should be within the document ready function.

In this function, the first thing we’ll do is work out the current scroll position of the page and save it in a variable to use later:

The .scrollTop()ย function returns where the scroll bar is for our selected element, in this case, we’re asking for it in regards to our body tag. Our scrollPositionย variable will now contain a number which is where the user currently is on the page, so at the very top, this will be zero.

We’re then just printing out that value to our console. So, if you open your page in a browser and pull up your console, you should see numbers being output as you’re scrolling your page.

You can now use a simple if statement to test if a user is past a pont: