Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
34
rated 0 times [  38] [ 4]  / answers: 1 / hits: 17365  / 9 Years ago, sat, january 16, 2016, 12:00:00

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;
});

More From » jquery

 Answers
51

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;
};
});

[#63705] Thursday, January 14, 2016, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kyla

Total Points: 77
Total Questions: 108
Total Answers: 111

Location: Grenada
Member since Mon, May 8, 2023
1 Year ago
;