Get scroll position in vanilla JavaScript Vanilla JS

Some website designs adapt once a user is scrolling or has scrolled to a specific point and some websites use scroll points to make functional changes such as loading more content.

This is how to get the scroll position once a user has scrolled in vanilla JavaScript.

window.addEventListener('scroll', function() {
    let scroll = window.scrollY;
    if (scroll > 0) {
        
    } else {
        
    }
});

If the user has a scrollY of 0, they are at the very top of the page. Some websites show a large navigation bar when the user is at the top, and a narrower fixed position navigation bar when scrolling.

If you plan to use specific scroll positions to make changes, you should consider that a particular scroll position on mobile may show different content to the same scroll position on desktop as content is often stacked or allowed to wrap for narrower viewports.
Instead of using a specific number of pixels, you can use JavaScript to get the number of pixels an element is vertically spaced from the top of the closest relatively positioned parent element. Use Element.offsetTop to get this value for an element and use this value to set your scroll point.
As this will be calculated for each user individually, you won't need to worry about the element on mobile being at a different scroll position to the same element on desktop, just use the calculated value.

This is how to check if a user has scrolled to a specific element on the page in vanilla JavaScript.

let sectionTwo = document.querySelector('#section-2');

window.addEventListener('scroll', function() {
    let scroll = window.scrollY;
    if (scroll > sectionTwo.offsetTop) {
        
    } else {
        
    }
});

You can use this to make changes once a user has scrolled to a specific element on the page. Changes could include animations such as fading elements in and moving elements or functional changes such as loading more content.

Thanks for reading.
Ryan

Published on 22 Mar 2019 (on a previous domain)
Last modified on 26 Jun 2022