Creating an autoscroll event to next slide/page of the size of the window. But every time I scroll, the event is triggered twice. I'm guessing because is detecting the autoscroll event as a trigger too and scrolling again. Is there a way to fix it?
var content = 0;
var scrolled = 0;
var contentNum = $('.content').length
var offset = $("#intro").offset();
var lastScrollTop = 0;
var timeout;
$(window).scroll(function() {
var st = $(this).scrollTop();
var scrolled = 0;
clearTimeout(timeout);
timeout = setTimeout(function() {
if (st > lastScrollTop){
scrolled = 1;
} else {
scrolled = -1;
}
if ( !(content == 0 && scrolled == -1) && !(content == (contentNum-1) && scrolled == +1) ){
content = content + scrolled;
offset = $(".content").eq(content).offset();
$('html').animate({
scrollTop: offset.top,
scrollLeft: offset.left
}, 500);
}
lastScrollTop = st;
}, 50);
});
Tried using global variable, but its still triggering twice.
You can use event.deltaY with .on("wheel") listener. You must control with isScrolling variable.
var content = 0;
var contentNum = $('.content').length;
var isScrolling = false;
$(window).on("wheel", function(event) {
if (isScrolling) return;
var delta = event.originalEvent.deltaY;
if (delta > 0 && content < contentNum - 1) {
console.log("up")
content++;
} else if (delta < 0 && content > 0) {
console.log("down")
content--;
} else {
return;
}
var offset = $(".content").eq(content).offset();
isScrolling = true;
$('html').animate({
scrollTop: offset.top,
scrollLeft: offset.left
}, 500, function() {
isScrolling = false;
});
});