I am trying to build a website that automatically scrolls to each section when the user scrolls the page up or down. I have been trying to solve this problem for weeks and would appreciate any help on the matter. I believe the problem is since the event handler is a scroll event which fires a scroll function this causes more than one scroll to occur. I have read many articles discussing this topic and the solution seems to be adding a setInterval or setTimeout function, but I have tried both and still no results.
var page = $("#page_container");
var home = $("#home");
var musicians = $("#musicians");
var athletes = $("#athletes");
var politics = $("#politics");
var bio = $("#bio");
var pages = [home, musicians, athletes, politics, bio];
var scrolled = false;
var pageCur = 0;
var lastScrollTop = 0;
page.scroll(function () {
scrolled = true;
});
var scrollTimeout = setInterval(function () {
if (scrolled == true) {
pageScroll();
}
else {
clearTimeout(scrollTimeout);
}
}, 3000);
function pageScroll() {
if (scrolled == true) {
scrolled = false;
var st = page.scrollTop();
var pageNex = pageCur + 1;
if (st > lastScrollTop) {
alert(pageNex);
pages[pageNex].velocity("scroll", {container: $("#page_container")});
} else {
alert(pageCur - 1);
pages[pageCur - 1].velocity("scroll", {container: $("#page_container")});
}
lastScrollTop = st;
pageCur = pageNex;
alert("1");
clearTimeout(scrollTimeout);
}
}
Indeed set a timeout :) I think you were close to the solution. Try this little code:
page.on('mousewheel', function (e) {
e.preventDefault();
if(Timeout)
return //if Timout == TRUE, then stop this function
Timeout = true //if Timout == FALSE, set TRUE and then execute
pageScroll(e) //scrollfunction to be called, Scrolling all the way!! YEAAH
setTimeout(function(){Timeout = false},250)//Set Timeout to False after 0.25s
});
function pageScroll(e) {
var st = page.scrollTop();
var pageNex = pageCur + 1;
if (st > lastScrollTop) {
alert(pageNex);
pages[pageNex].velocity("scroll", {container: $("#page_container")});
} else {
alert(pageCur - 1);
pages[pageCur - 1].velocity("scroll", {container: $("#page_container")});
}
lastScrollTop = st;
pageCur = pageNex;
alert("1");
e.preventDefault();
}
Check This fiddle for a working example!
Hope it helped :)
EDIT: A working fiddle added!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With