Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery - carry out function after scroll past x pixels [duplicate]

I've made a nav on my site which is absolute positioned.

I've made a class to make this fixed to the top of the screen.

What I'm trying to find out is how to carry out a function (toggleClass in this instance) after the windows has been scrolled x amount of pixels down the page (500 px in this instance)

like image 531
Aero Avatar asked Jan 22 '26 09:01

Aero


1 Answers

The procedure is:

  • Listen to the scroll event to detect the user's scroll position as they scroll
  • Calculate the element's position from the top of the page, or determine fixed distance from the top of the page (500px, in your example)
  • When the scroll position is greater than the trigger position, execute the function. If you only want the function to fire once, remove the scroll listener in the function.

Assuming jQuery, something like this:

$(window).on('scroll', function() {
    scrollPosition = $(this).scrollTop();
    if (scrollPosition >= 500) {
        // If the function is only supposed to fire once
        $(this).off('scroll');

        // Other function stuff here...
    }
});
like image 99
ebuat3989 Avatar answered Jan 23 '26 22:01

ebuat3989