Menü schliessen
Created: February 19th 2021
Categories: IT Development,  JavaScript Development
Author: Marcus Fleuti

[HOW TO] Measure scroll distance with JQuery

Tags:  header,  jQuery,  measure,  pixel,  scroll,  window
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

Maybe you need to create a header which minifies on scroll or changes color. To apply these styles to e.g. the header we need to measure the "scroll-distance" from the top in px (for best results i would recommend using pixels).

How-To

To get the scroll-measurements you need to (most probably) use JQuery.

Firstly we have to make sure that the user is scrolling the window, which can be achieved by using the function below:

$(window).scroll(function (){ }

After we checked for the scroll-event, it's important to get the value for which has been scrolled. We can get the current scroll-value like below:

let scroll = $(window).scrollTop();

If you are combining these two functions you can check for some scroll-points (in px) where you need to change the header or something else. This would look something like that:

$(window).scroll(function (){
    let scroll = $(window).scrollTop();
    if(scroll >= 350) {
       /* insert what happens after scroll bigger than 350px */
    } else {
       /* insert what happens when the user scrolls back to less than 350px */
    }
})