Stopping fullpage.js SetInterval - javascript

I have used fullpage.js on my website's homepage, and I have made it so that it scrolls automatically every 10 seconds.
I have used the function as it is below:
$( '#fullpage' ).fullpage({
continuousVertical: true,
loopHorizontal: false,
resize: false,
afterRender: function() { // so that it applies to first section too
forceScroll();
}
});
slideTimeout = setInterval( function() {
$.fn.fullpage.moveSectionDown();
}, 10000);
function forceScroll() {
var slideTimeout;
}
However, I'd like to use clearInterval(slideTimeout) when the user slides down or sideways using his mouse, as when I want to browse afterwards it keeps going up and down... which is really annoying.
But I can't seem to find the trigger for it, or any workaround really!
How am I able to make this work?
Documentation for Fullpage.js on GitHub;
The website I am speaking about
Thank you a lot in advance,
Filipe

If I understand true, you want to unbind your interval when user scrolls.
$('body').on('mousewheel', function(e) {
if (e.originalEvent.wheelDelta > 0) {
if (typeof slideTimeout !== "undefined") {
clearInterval(slideTimeout); //case for scroll up
alert("Timeout clear");
}
} else {
if (typeof slideTimeout !== "undefined") {
clearInterval(slideTimeout); //case for scroll down
alert("Timeout clear");
}
}
});
Here is an example version of the system
var slideInterval = setInterval(function() {
$("#counter").text(parseInt($("#counter").text()) + 1);
}, 1000);
$('body').on('mousewheel', function(e) {
if (e.originalEvent.wheelDelta > 0) {
clearInterval(slideInterval);
alert("Timeout clear");
} else {
clearInterval(slideInterval);
alert("Timeout clear");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="counter" style="height:6000px;">0</div>

fullpage.js doesn't provide any callback for mouse wheel /trackpad events I'm afraid.
You would have to do it by yourself as #Ahmet Can Güven indicates. But I would recommend you to look for a more cross browser solution mousewheel won't work in all browsers.

Related

jQuery "Snap To" Effect

I have a specific effect I want for a website I'm building. As you can see in this website, I want the screen to "snap to" the next section after the user scrolls, but only after (not the instant) the scroll event has fired. The reason I don't want to use a plugin like panelSnap is because I
1: Want smaller code and
2. Want the website, when viewed on mobile, to have more of the "instant snap" effect (try reducing the browser size in the website mentioned above). I know I theoretically could try combining two plugins, like panelsnap and scrollify, and activate them appropriately when the browser is a certain width, but I don't know if I want to do that... :(
So all of that said, here's the code:
var scrollTimeout = null;
var currentElem = 0;
var options = {
scrollSpeed: 1100,
selector: 'div.panels',
scrollDelay: 500,
};
$(document).ready(function() {
var $snapElems = $(options.selector);
console.log($($snapElems[currentElem]).offset().top);
function snap() {
if ($('html, body').scrollTop() >= $($snapElems[currentElem]).offset().top) {
if (currentElem < $snapElems.length-1) {
currentElem++;
}
}else{
if (currentElem > 0) {
currentElem = currentElem - 1;
}
}
$('html, body').animate({
scrollTop: $($snapElems[currentElem]).offset().top
}, options.scrollSpeed);
}
$(window).scroll(function() {
if ($(window).innerWidth() > 766) {
if (scrollTimeout) {clearTimeout(scrollTimeout);}
scrollTimeout = setTimeout(function(){snap()}, options.scrollDelay);
}else{
//I'll deal with this later
}
});
});
My problem is that every time the snap function is called, it triggers the scroll event, which throws it into a loop where the window won't stop scrolling between the first and second elements. Here's the poor, dysfunctional site: https://tcfchurch.herokuapp.com/index.html Thank for the help.
You can use a boolean to record when the scroll animation in snap is in progress and prevent your $(window).scroll() event handler from taking any action.
Here's a working example:
var scrollTimeout = null;
var currentElem = 0;
var options = {
scrollSpeed: 1100,
selector: 'div.panels',
scrollDelay: 500,
};
$(document).ready(function() {
var scrollInProgress = false;
var $snapElems = $(options.selector);
console.log($($snapElems[currentElem]).offset().top);
function snap() {
if ($('html, body').scrollTop() >= $($snapElems[currentElem]).offset().top) {
if (currentElem < $snapElems.length-1) {
currentElem++;
}
}else{
if (currentElem > 0) {
currentElem = currentElem - 1;
}
}
scrollInProgress = true;
$('html, body').animate({
scrollTop: $($snapElems[currentElem]).offset().top
}, options.scrollSpeed, 'swing', function() {
// this function is invoked when the scroll animate is complete
scrollInProgress = false;
});
}
$(window).scroll(function() {
if (scrollInProgress == false) {
if ($(window).innerWidth() > 766) {
if (scrollTimeout) {clearTimeout(scrollTimeout);}
scrollTimeout = setTimeout(function(){snap()}, options.scrollDelay);
}else{
//I'll deal with this later
}
}
});
});
The variable scrollInProgress is set to false by default. It is then set to true when the scroll animate starts. When the animate finishes, scrollInProgress is set back to false. A simple if statement at the top of your $(window).scroll() event handler prevents the handler from taking any action while the animate scroll is in progress.
Have you considered using the well known fullPage.js library for that? Check out this normal scroll example. The snap timeout is configurable through the option fitToSectionDelay.
And nothing to worry about the size... it is 7Kb Gzipped!
I know I theoretically could try combining two plugins, like panelsnap and scrollify, and activate them appropriately when the browser is a certain width, but I don't know if I want to do that
fullPage.js also provides responsiveWidth and responsiveHeight options to turn it off under certain dimensions.

Increasing/decreasing audio on a video element, triggered via jQuery Waypoints

I have a page with a series of (HTML 5) videos whose audio needs to fade in or out depending on your position on the page (and it may be different for each video). I'm using jQuery Waypoints with the InView plugin to detect when an element is in the viewport. I'm not sure how to do it consistently, so that you don't cause unexpected behavior when you trip a waypoint while the volume is still decreasing or increasing.
var waypoint = new Waypoint.Inview({
element: $('#element')[0],
enter: function() {
$('#element')[0].volume = 0;
$('#ielement')[0].play();
incVol($('#element')[0]);
},
entered: function() {},
exit: function() {},
exited: function() {
decVol($('#element')[0]);
}
});
function incVol(e) {
setTimeout(function() {
if ((e.volume + .05) < 1) {
e.volume += .05;
incVol(e);
} else {
e.vol = 1;
}
}, 100)
}
function decVol(e) {
setTimeout(function() {
if ((e.volume - .05) > 0) {
e.volume -= .05;
decVol(e);
} else {
e.volume = 0;
e.pause();
}
}, 100)
}
This is an inconsistent attempt, if you trigger 'enter' while 'decVol' is still running you lose volume completely and have to trigger an 'exit', wait, and then trigger 'enter' again.
I've also tried something with jQuery's animate on volume. But that doesn't seem consistent either.
var waypoint = new Waypoint.Inview({
element: $('#element')[0],
enter: function() {
$('#element')[0].volume = 0;
$('#element')[0].play();
$('#element').animate({
volume: 1
}, 1000);
},
entered: function() {},
exit: function() {},
exited: function() {
$('#element').animate({
volume: 0
}, 1000, function() {
$('#element')[0].pause();
});
}
});
If I scroll up and down too fast, especially if I have multiple waypoints of this type in the page, then the queue of events becomes extensive and I have fade ins/outs happening far after the events have triggered (though, I prefer this implementation for the moment).
Any suggestions on how to achieve what I want a little better?
Prefacing the animate() function with stop() is the answer.
Something like:
$('#element').stop(true, false).animate({
volume: 1
}, 1000);

Slide down and slide up events mixed up in a fast mouse wheel up and down

I'm using jquery slideDown() and slideUp() to show a fixed gototop link when the scroll bar height is more than 200px.
Problem:
Link slide action mixed up in a fast mouse wheel up and down. Because of 0.4 sec running time of slide functions. I tried to define a visible flag and complete functions to prevent mixing. But not successful.
JsFiddle
Scroll down in result block to view the link and try a fast wheel up and down. If the result block has big height on your screen, please decrease the height to see the action.
impress: function () {
if ($(window).scrollTop() > this.MIN_SCROLL_HEIGHT
&& !this.buttonVisibleFlag)
{
this.button.slideDown(400, function() {
Blue.buttonVisibleFlag = true;
});
}
else if ($(window).scrollTop() <= this.MIN_SCROLL_HEIGHT
&& this.buttonVisibleFlag)
{
this.button.slideUp(400, function() {
Blue.buttonVisibleFlag = false;
});
}
}
Any ideas or help would be greatly appreciated.
I think your best bet would be to perform the sliding actions only after the user has stopped scrolling for a certain (small) period of time. I found this method to detect when the user stops scrolling and implemented in your code, here's the result:
Updated fiddle
var Blue = {
MIN_SCROLL_HEIGHT: 200,
button: null,
buttonVisibleFlag: null,
init: function () {
this.button = $(".gototop");
this.buttonVisibleFlag = false;
this.setWindowBindings();
},
setWindowBindings: function () {
$(window).scroll(function () {
//perform actions only after the user stops scrolling
clearTimeout($.data(this, 'scrollTimer'));
$.data(this, 'scrollTimer', setTimeout(function () {
Blue.impress();
}, 150));
});
},
impress: function () {
if ($(window).scrollTop() > this.MIN_SCROLL_HEIGHT) {
this.button.slideDown();
} else if ($(window).scrollTop() <= this.MIN_SCROLL_HEIGHT) {
this.button.slideUp();
}
}
}
$(document).ready(function () {
Blue.init();
});
Note: you may want to tweak the timeout interval to suit your needs

Cancel scrolling after user interaction

My webpage animates scrolling when users click on links to the same page. I want to cancel this animation as soon as the user tries to scroll (otherwise the user and the browser are fighting for control) – no matter whether with the mouse wheel, the keyboard or the scrollbar (or any other way – are there other ways of scrolling?). I managed to cancel the animation after the mouse wheel or keyboard are used, how do I get this working with the scrollbar?
Here is how my code looks for the keyboard:
$(document.documentElement).keydown( function (event) {
if(event.keyCode == 38 || 40) stopScroll();
});
function stopScroll() {
$("html, body").stop(true, false);
}
I also tried a more elegant way of doing this by using scroll(), the problem is that scroll() catches everything including the animated and automated scrolling. I could not think of any way to let it catch all scrolling except the animated scrolling.
you need animation marker, something like this
$("html, body").stop(true, false).prop('animatedMark',0.0).animate({scrollTop : top, animatedMark: '+=1.0'})
Here is the code, the code was mix of GWT and javascript so moved it to js, not fully tested, please try it
var lastAnimatedMark=0.0;
function scrollToThis(top){
// Select/ stop any previous animation / reset the mark to 0
// and finally animate the scroll and the mark
$("html, body").stop(true, false).prop('animatedMark',0.0).
animate({scrollTop : top, animatedMark: '+=1.0'}
,10000,function(){
//We finished , nothing just clear the data
lastAnimatedMark=0.0;
$("html, body").prop('animatedMark',0.0);
});
}
//Gets the animatedMark value
function animatedMark() {
var x=$("html, body").prop('animatedMark');
if (x==undefined){
$("html, body").prop('animatedMark', 0.0);
}
x=$("html, body").prop('animatedMark');
return x;
};
//Kills the animation
function stopBodyAnimation() {
lastAnimatedMark=0;
$("html, body").stop(true, false);
}
//This should be hooked to window scroll event
function scrolled(){
//get current mark
var currentAnimatedMark=animatedMark();
//mark must be more than zero (jQuery animation is on) & but
//because last=current , this is user interaction.
if (currentAnimatedMark>0 && (lastAnimatedMark==currentAnimatedMark)) {
//During Animation but the marks are the same !
stopBodyAnimation();
return;
}
lastAnimatedMark=currentAnimatedMark;
}
Here is the blog about it
http://alaamurad.com/blog/#!canceling-jquery-animation-after-user-interaction
Enjoy!
Here's a jquery function that should do the trick:
function polite_scroll_to(val, duration, callback) {
/* scrolls body to a value, without fighting the user if they
try to scroll in the middle of the animation. */
var auto_scroll = false;
function stop_scroll() {
if (!auto_scroll) {
$("html, body").stop(true, false);
}
};
$(window).on('scroll', stop_scroll);
$("html, body").animate({
scrollTop: val
}, {
duration: duration,
step: function() {
auto_scroll = true;
$(window).one('scroll', function() {
auto_scroll = false;
});
},
complete: function() {
callback && callback();
},
always: function() {
$(window).off('scroll', stop_scroll);
}
});
};
It's not very elegant, but you could use a flag of some kind to detect what type of scrolling you're dealing with (animated or 'manual') and always kill it when it's animated. Here's an untested example:
var animatedScroll = false;
// you probably have a method looking something like this:
function animatedScrollTo(top) {
// set flag to true
animatedScroll = true;
$('html').animate({
scrollTop : top
}, 'slow', function() {
// reset flag after animation is completed
animatedScroll = false;
});
}
function stopScroll() {
if (animatedScroll) {
$("html, body").stop(true, false);
}
}

Event when user stops scrolling

I'd like to do some fancy jQuery stuff when the user scrolls the page. But I have no idea how to tackle this problem, since there is only the scroll() method.
Any ideas?
You can make the scroll() have a time-out that gets overwritten each times the user scrolls. That way, when he stops after a certain amount of milliseconds your script is run, but if he scrolls in the meantime the counter will start over again and the script will wait until he is done scrolling again.
Update:
Because this question got some action again I figured I might as well update it with a jQuery extension that adds a scrollEnd event
// extension:
$.fn.scrollEnd = function(callback, timeout) {
$(this).on('scroll', function(){
var $this = $(this);
if ($this.data('scrollTimeout')) {
clearTimeout($this.data('scrollTimeout'));
}
$this.data('scrollTimeout', setTimeout(callback,timeout));
});
};
// how to call it (with a 1000ms timeout):
$(window).scrollEnd(function(){
alert('stopped scrolling');
}, 1000);
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<div style="height: 200vh">
Long div
</div>
Here is a simple example using setTimeout to fire a function when the user stops scrolling:
(function() {
var timer;
$(window).bind('scroll',function () {
clearTimeout(timer);
timer = setTimeout( refresh , 150 );
});
var refresh = function () {
// do stuff
console.log('Stopped Scrolling');
};
})();
The timer is cleared while the scroll event is firing. Once scrolling stops, the refresh function is fired.
Or as a plugin:
$.fn.afterwards = function (event, callback, timeout) {
var self = $(this), delay = timeout || 16;
self.each(function () {
var $t = $(this);
$t.on(event, function(){
if ($t.data(event+'-timeout')) {
clearTimeout($t.data(event+'-timeout'));
}
$t.data(event + '-timeout', setTimeout(function () { callback.apply($t); },delay));
})
});
return this;
};
To fire callback after 100ms of the last scroll event on a div (with namespace):
$('div.mydiv').afterwards('scroll.mynamespace', function(e) {
// do stuff when stops scrolling
$(this).addClass('stopped');
}, 100
);
I use this for scroll and resize.
Here is another more generic solution based on the same ideas mentioned:
var delayedExec = function(after, fn) {
var timer;
return function() {
timer && clearTimeout(timer);
timer = setTimeout(fn, after);
};
};
var scrollStopper = delayedExec(500, function() {
console.log('stopped it');
});
document.getElementById('box').addEventListener('scroll', scrollStopper);
I had the need to implement onScrollEnd event discussed hear as well.
The idea of using timer works for me.
I implement this using JavaScript Module Pattern:
var WindowCustomEventsModule = (function(){
var _scrollEndTimeout = 30;
var _delayedExec = function(callback){
var timer;
return function(){
timer && clearTimeout(timer);
timer = setTimeout(callback, _scrollEndTimeout);
}
};
var onScrollEnd = function(callback) {
window.addEventListener('scroll', _delayedExec(callback), false);
};
return {
onScrollEnd: onScrollEnd
}
})();
// usage example
WindowCustomEventsModule.onScrollEnd(function(){
//
// do stuff
//
});
Hope this will help / inspire someone
Why so complicated? As the documentation points out, this http://jsfiddle.net/x3s7F/9/ works!
$('.frame').scroll(function() {
$('.back').hide().fadeIn(100);
}
http://api.jquery.com/scroll/.
Note: The scroll event on Windows Chrome is differently to all others. You need to scroll fast to get the same as result as in e.g. FF. Look at https://liebdich.biz/back.min.js the "X" function.
Some findings from my how many ms a scroll event test:
Safari, Mac FF, Mac Chrome: ~16ms an event.
Windows FF: ~19ms an event.
Windows Chrome: up to ~130ms an event, when scrolling slow.
Internet Explorer: up to ~110ms an event.
http://jsfiddle.net/TRNCFRMCN/1Lygop32/4/.
There is no such event as 'scrollEnd'. I recommend that you check the value returned by scroll() every once in a while (say, 200ms) using setInterval, and record the delta between the current and the previous value. If the delta becomes zero, you can use it as your event.
There are scrollstart and scrollstop functions that are part of jquery mobile.
Example using scrollstop:
$(document).on("scrollstop",function(){
alert("Stopped scrolling!");
});
Hope this helps someone.
The scrollEnd event is coming. It's currently experimental and is only supported by Firefox. See the Mozilla documentation here - https://developer.mozilla.org/en-US/docs/Web/API/Document/scrollend_event
Once it's supported by more browsers, you can use it like this...
document.onscrollend = (event) => {
console.log('Document scrollend event fired!');
};
I pulled some code out of a quick piece I cobbled together that does this as an example (note that scroll.chain is an object containing two arrays start and end that are containers for the callback functions). Also note that I am using jQuery and underscore here.
$('body').on('scroll', scrollCall);
scrollBind('end', callbackFunction);
scrollBind('start', callbackFunction);
var scrollCall = function(e) {
if (scroll.last === false || (Date.now() - scroll.last) <= 500) {
scroll.last = Date.now();
if (scroll.timeout !== false) {
window.clearTimeout(scroll.timeout);
} else {
_(scroll.chain.start).each(function(f){
f.call(window, {type: 'start'}, e.event);
});
}
scroll.timeout = window.setTimeout(self.scrollCall, 550, {callback: true, event: e});
return;
}
if (e.callback !== undefined) {
_(scroll.chain.end).each(function(f){
f.call(window, {type: 'end'}, e.event);
});
scroll.last = false;
scroll.timeout = false;
}
};
var scrollBind = function(type, func) {
type = type.toLowerCase();
if (_(scroll.chain).has(type)) {
if (_(scroll.chain[type]).indexOf(func) === -1) {
scroll.chain[type].push(func);
return true;
}
return false;
}
return false;
}

Categories

Resources