Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll Function Firing Multiple Times Instead of Once

I am trying to create a website that automatically scrolls to each section upon a single scroll action. This means that the code has to check if the page is scrolled up or scrolled down. I believe the code below solves my problem but the scroll action is fired more than once while the page is scrolling. You will see that the first alert in the if statement reaches 5 instead of the desired 1. Any help on the matter would be highly appreciated.

[Note] I am using the velocity.js library to scroll to each section within the container.

var page = $("#content-container");
var home = $("#home-layer-bottom");
var musicians = $("#musicians");
var athletes = $("#athletes");
var politics = $("#politics");
var bio = $("#politics");
var pages = [ home,musicians,athletes,politics,bio ];

var pageCur = 0;


var lastScrollTop = 0;
page.scroll(function(){

var st = $(this).scrollTop();
var pageNex = pageCur + 1;

if (st > lastScrollTop){
    alert(pageNex);
pages[pageNex].velocity("scroll", { container: $("#content-container") });
} else {
   alert(pageCur-1);
pages[pageCur-1].velocity("scroll", { container: $("#content-container") });
}
lastScrollTop = st;
pageCur = pageNex;
});
like image 980
Andrew Denaro Avatar asked Jan 16 '16 00:01

Andrew Denaro


People also ask

How often does scroll event fire?

The scroll event fires when the document view has been scrolled. For element scrolling, see Element: scroll event . Note: In iOS UIWebViews, scroll events are not fired while scrolling is taking place; they are only fired after the scrolling has completed. See Bootstrap issue #16202.

What triggers a scroll event?

The scroll event occurs when the user scrolls in the specified element. The scroll event works for all scrollable elements and the window object (browser window). The scroll() method triggers the scroll event, or attaches a function to run when a scroll event occurs.

What is window Onscroll in Javascript?

Definition and Usage. The onscroll event occurs when an element's scrollbar is being scrolled. Tip: use the CSS overflow style property to create a scrollbar for an element.


1 Answers

The scroll event (as well as the resize event) fire multiple times as a user does this. To help this, the best practice is to debounce. However, I've never gotten that to work. Instead, I use a global boolean to check if the function has fired.

var scrolled = false;
page.on('scroll', function(){
    if(!scrolled){
        scrolled = true;
        //do stuff that should take a while...
        scrolled = false;
    };
});
like image 165
Donnie D'Amato Avatar answered Oct 14 '22 13:10

Donnie D'Amato