Get Vertical Scroll Position Using jQuery

Finding the current vertical scroll position of a web page or an individual element is a common task when building features like sticky navigation bars, progress bars, or scroll-triggered animations. This article provides a clear, step-by-step guide on how to use jQuery to accurately detect and track the vertical scroll position of the browser window or any scrollable container.

The .scrollTop() Method

In jQuery, the primary method for retrieving the vertical scroll position is .scrollTop(). This method returns the number of pixels that are currently hidden from view above the scrollable area.

1. Getting the Window's Scroll Position

To get the vertical scroll position of the entire browser window, target the window object:

let scrollPosition = $(window).scrollTop();
console.log("Current vertical position: " + scrollPosition + "px");

When the page is at the very top, $(window).scrollTop() returns 0. As you scroll down, this number increases in direct proportion to the number of pixels scrolled.

2. Getting a Specific Element's Scroll Position

If you have an overflow: auto or overflow: scroll <div> or other element, you can measure its internal scroll position by targeting that specific element's selector:

let elementScroll = $("#scrollableContainer").scrollTop();
console.log("Element scroll position: " + elementScroll + "px");

Tracking the Scroll Position Dynamically

To monitor changes to the vertical scroll position in real time as the user moves down the page, attach the .scrollTop() call to jQuery's .scroll() event listener:

$(window).on("scroll", function() {
    let currentPosition = $(this).scrollTop();
    
    if (currentPosition > 200) {
        // Trigger action after scrolling down 200px
        $("#backToTopButton").fadeIn();
    } else {
        $("#backToTopButton").fadeOut();
    }
});

Summary of Differences

  • $(window).scrollTop(): Measures the distance from the top of the entire document viewport.
  • $(element).scrollTop(): Measures the distance scrolled inside a specific container with its own scrollbars.
  • Setter Usage: While calling .scrollTop() without arguments retrieves the position, passing a numeric value (e.g., $(window).scrollTop(500)) will immediately set the scroll position to that offset.