JQuery Scroll Event keeps firing when you scroll more

So I have a scroll event that fires when the user scrolls to a certain point on the site. It works until you hit that point and want to keep scrolling, then it will fire continuously with every single scroll. I want to fire ONE time and then just not fire anymore.

    $(window).on('scroll', function() {
    var y_scroll_pos = window.pageYOffset;
    var scroll_pos_test = 450;  // set to whatever you want it to be

    if(y_scroll_pos > scroll_pos_test) {
      alert("hey you hit it");
    }
});

I set up a demo below:

JSFiddle

Answers 1

  • Of course it keeps firing with every scroll - you haven't removed the scroll event handler, and if the user keeps scrolling down the if condition will continue to be true for subsequent scroll events. Note that the handler is also firing for every scroll before the user reaches that point of the page, it just doesn't do anything noticeable because of the if.

    "I want to fire ONE time and then just not fire anymore."

    The obvious solution would be to just call the .off() method to remove the scroll handler once it's no longer required:

    $(window).on('scroll', function() {
        var y_scroll_pos = window.pageYOffset;
        var scroll_pos_test = 450;  // set to whatever you want it to be
    
        if(y_scroll_pos > scroll_pos_test) {
          $(window).off('scroll');  // <--- add this
          alert("hey you hit it");
        }
    });
    

Related Articles