Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animated Scroll on Page Up/Down Event

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

    }
}
like image 667
Andrew Denaro Avatar asked Feb 06 '16 21:02

Andrew Denaro


1 Answers

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!

like image 90
Evochrome Avatar answered Nov 03 '22 10:11

Evochrome