Jquery Full Page Scroll Without Plugin
https://jsfiddle.net/dewit/xnq0pzx0/1/ var currentLocation = 'firstPage'; $(document).scroll(function(e){ var scrolled = $(window).scrollTop(), secondHeight = $('#seco
Solution 1:
The problem is that the event listener is triggered when the user scrolls and also by your animation. From what I see, you want to check all the if/else statements only when user scrolls. Something like the following should help:
var currentLocation = 'firstPage';
// No need to set these inside the event listener since they are always the same.var firstHeight = $('#firstPage').offset().top,
secondHeight = $('#secondPage').offset().top,
thirdHeight = $('#thirdPage').offset().top;
// Helper so we can check if the scroll is triggered by user or by animation.var autoScrolling = false;
$(document).scroll(function(e){
var scrolled = $(window).scrollTop();
// Only check if the user scrolledif (!autoScrolling) {
if (scrolled > 1 && currentLocation == 'firstPage') {
scrollPage(secondHeight, 'secondPage');
} elseif (scrolled > secondHeight + 1 && currentLocation == 'secondPage') {
scrollPage(thirdHeight, 'thirdPage');
} elseif (scrolled < thirdHeight - 1 && currentLocation == 'thirdPage') {
scrollPage(secondHeight, 'secondPage');
} elseif (scrolled < secondHeight - 1 && currentLocation == 'secondPage') {
scrollPage(firstHeight, 'firstPage');
}
}
// Since they all have the same animation, you can avoid repetitionfunctionscrollPage(nextHeight, page) {
currentLocation = page;
// At this point, the page will start scrolling by the animation// So we switch this var so the listener does not trigger all the if/else
autoScrolling = true;
$('body,html').animate({scrollTop:nextHeight}, 500, function () {
// Once the animation is over, we can reset the helper.// Now it is back to detecting user scroll.
autoScrolling = false;
});
}
$('h1').html(scrolled);
$('h1').append("/" + secondHeight);
$('h1').append("/" + thirdHeight);
})
*{
padding: 0;
margin: 0;
}
html,body{
width: 100%;
height:100%;
}
.page{
width: 100%;
line-height: 100vh;
text-align: center;
}
header{
position: fixed;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><header><h1></h1></header><article><divclass="page"id="firstPage"><h2>first page</h2></div><divclass="page"id="secondPage"><h2>second page</h2></div><divclass="page"id="thirdPage"><h2>third page</h2></div></article>
Post a Comment for "Jquery Full Page Scroll Without Plugin"