How to detect "scrollstop" event in a browser - javascript

I know that there is no scrollstop event in an official browser DOM documentation but how to detect it?

The most logical way to do this is to listen for a timeout.
var timer = null;
var timeout = 150; //ms
window.addEventListener('scroll', function() {
if(timer !== null) {
clearTimeout(timer);
}
timer = setTimeout(function() {
// do something
}, timeout);
}, false);
If it is still not scroll after 150ms it means the scroll has stopped!
You can change this timeout as you see fit. Again, I think the most logical thing is to choose a value between 150 and 250ms.
var timer = null;
var timeout = 150; //ms
window.addEventListener('scroll', function() {
if (timer !== null) {
clearTimeout(timer);
}
timer = setTimeout(function() {
console.log('Scroll Stopped');
}, timeout);
}, false);
html,
body {
padding-top: 100rem;
}

Related

Scripts crashing each other

well my problem is hopefully easy: 3 actions that shall happen while hovering a photo. The timer at the bottom works now, the other things crashed. A Page shall open in 5 seconds and the photo shall move out of the display before. Sounds easy, doesnt it? I hope so.
Do you guys know what I can do?
Thanks already and best regards!
<script>
var interval;
var timer = 5;
$('.HoverBalken').on({'mouseover': function () {
timer = setTimeout(function () {
$('.HoverBalken').toggleClass('HoverBalken-active');
$('.N').toggleClass('N-active');
$('.K').toggleClass('K-active');
}, );
timer = setTimeout(function () {
window.location = "FoliagePlates.html"
}, 5000);
}, 'mouseover': function () {
interval = setInterval(function() {
timer--;
$('.timer').text(timer);
if (timer === 0) clearInterval(interval);
}, 1000);
}, 'mouseout' : function () {
clearTimeout(timer);
$('.HoverBalken').removeClass('HoverBalken-active');
$('.N').removeClass('N-active');
$('.K').removeClass('K-active');
clearInterval(interval);
timer = 5;
$('.timer').text(timer);
}
});
</script>
<script>
var interval;
var timer = 5;
var timeout1,timeout2;
$('.HoverBalken')
.mouseover(function() {
//use different variable than your timer
timeout1 = setTimeout(function () {
$('.HoverBalken').toggleClass('HoverBalken-active');
$('.N').toggleClass('N-active');
$('.K').toggleClass('K-active');
}, 2000); //forgot time here
//use different variable than your timer and first timeout
timeout2 = setTimeout(function () {
window.location = "FoliagePlates.html"
}, 5000);
//stay in same scope, don't define event again
interval = setInterval(function() {
timer--;
$('.timer').text(timer);
if (timer === 0) clearInterval(interval);
}, 1000);
})
.mouseout(function() {
//clear both timers
clearTimeout(timeout1);
clearTimeout(timeout2);
$('.HoverBalken').removeClass('HoverBalken-active');
$('.N').removeClass('N-active');
$('.K').removeClass('K-active');
clearInterval(interval);
timer = 5;
$('.timer').text(timer);
});
</script>
this should fix it, notice the comments in code

Javascript, run function for 0.5 seconds then stop (Loop)

I'm running a node server with raspberry pi gpio modules installed. I'm trying to get my ESC to start and run for 0.5 seconds, then I need it to stop for .5 second, then start again in a loop. however if "start" = 0 (Button off) I need the loop to stop completely and set the servo pulse width to 1000 (Motor Stop)
Here is my code, It kinda works. But doesn't stop
var start = new blynk.VirtualPin(4);
start.on('write', function t(start) {
if (start == 1) {
setInterval(function() {
setInterval(function() {
motor.servoWrite(1920);
}, 500);
setInterval(function() {
motor.servoWrite(1000);
}, 1000);
}, 500);
} else {
motor.servoWrite(1000);
}
motor.servoWrite(1000);
});
Could someone show me where I've gone wrong?
Store your interval in a variable
var myInterval = setInterval(function() { [... your code code] },delay);
then to stop it by
clearInterval(myInterval);
var start = new blynk.VirtualPin(4);
motor.servoWrite(1000);
var interval, timeout;
start.on('write', function t(start) {
if (start == 1) {
clearInterval(interval);
clearTimeout(timeout);
interval = setInterval(function() {
motor.servoWrite(1920);
timeout = setTimeout(function() {
motor.servoWrite(1000);
}, 500);
}, 1000);
} else {
clearInterval(interval);
clearTimeout(timeout);
motor.servoWrite(1000);
}
});
I think setInterval might be the wrong thing to use. The setInterval is reoccurring. Where you really just want to run something once, wait, then run something else. Try doing it with setTimeout, it waits for x ms then executes something.
var id = null;
start.on('write', function t(start) {
if(start == 1){
pulse();
}
else {
clearTimeout(id);
motor.servoWrite(1000);
}
});
function pulse() {
servoOn();
id = setTimeout(function(){
servoOff();
id = setTimeout(function(){
pulse();
}, 1000);
}, 500);
}
function servoOn(){
motor.servoWrite(1920);
}
function servoOff(){
motor.servoWrite(1000);
}

check if the page is on the top of the window

I need to check if an html page is on the top of the window or not.
So, i am using this code:
$(window).scroll(function(){
a = ($(window).scrollTop());
if (a>0) {
alert('page not in top');
}
});
But this is not working as expected because the event should be fired only when the user stops the scroll action. Any idea?
Try this:
var timer = null;
$(window).addEventListener('scroll', function() {
if(timer !== null) {
clearTimeout(timer);
}
timer = setTimeout(function() {
// do something
}, 150);
}, false);
Or this one:
var timer;
$(window).bind('scroll',function () {
clearTimeout(timer);
timer = setTimeout( refresh , 150 );
});
var refresh = function () {
// do stuff
console.log('Stopped Scrolling');
};
Use setTimeout:
var timeout;
$(window).scroll(function() {
clearTimeout(timeout);
timeout = setTimeout(function(){
a = $(window).scrollTop();
if ( a > 0 ) {
alert('page not in top');
}
}, 100);
});

Setinterval with exponential time decrease

I've got a mousedown event with a setinterval. I want the time of intervals to be variable. So the first one is 500, the second one 500/2 = 250, etc. Any tips?
$plus.mousedown(function(e) {
increment(20)
timeout = setInterval(function(){
increment(20)
}, 500);
});
$(document).mouseup(function(){
clearInterval(timeout);
return false;
});
Cheers!
EDIT: sorry for the ambiguity. I want the time of interval to change during the mousedown. So while the mousedown is being performed the intervaltime should change. So not by every single mouse click but with every continuous click, and then reset it again.
You can't really do this with setInterval() unless you keep clearing for a delay change, so you might as well write a wrapper around setTimeout() to accomplish something similar:
function easingTimeout(delay, fn)
{
var id,
invoker = function() {
fn();
delay = Math.floor(delay / 2);
if (delay) {
id = setTimeout(invoker, delay);
} else {
id = null;
}
}
// start it off
id = setTimeout(invoker, delay);
return {
clear: function() {
if (id) {
clearTimeout(id);
id = null;
}
}
}
To use:
var timeout;
$plus.mousedown(function(e) {
increment(20);
timeout = easingTimeout(500, function() {
increment(20);
});
});
$(document).mouseup(function(){
timeout.clear();
return false;
});
This solution does not depend on jQuery:
var timeoutInterval = 500;
var mousedown = false;
function incrementAndWait() {
if (!mousedown) return;
increment(20);
timeout = setTimeout(incrementAndWait, timeoutInterval);
timeoutInterval /= 2;
}
document.onmousedown = function() {
timeoutInterval = 500; // Reset to 500 to allow multiple mousedown/mouseup
mousedown = true;
incrementAndWait();
};
document.onmouseup = function() {
mousedown = false;
}
You can add console.log((new Date).getTime(), 20); to the incrementAndWait method to see the numbers going on the console. Something fun to play with :)

How do I know when I've stopped scrolling?

How do I know when I've stopped scrolling using Javascript?
You can add an event handler for the scroll event and start a timeout. Something like:
var timer = null;
window.addEventListener('scroll', function() {
if(timer !== null) {
clearTimeout(timer);
}
timer = setTimeout(function() {
// do something
}, 150);
}, false);
This will start a timeout and wait 150ms. If a new scroll event occurred in the meantime, the timer is aborted and a new one is created. If not, the function will be executed. You probably have to adjust the timing.
Also note that IE uses a different way to attach event listeners, this should give a good introduction: quirksmode - Advanced event registration models
There isn't a "Stopped Scrolling" event. If you want to do something after the user has finished scrolling, you can set a timer in the "OnScroll" event. If you get another "OnScroll" event fired then reset the timer. When the timer finally does fire, then you can assume the scrolling has stopped. I would think 500 milliseconds would be a good duration to start with.
Here's some sample code that works in IE and Chrome:
<html>
<body onscroll="bodyScroll();">
<script language="javascript">
var scrollTimer = -1;
function bodyScroll() {
document.body.style.backgroundColor = "white";
if (scrollTimer != -1)
clearTimeout(scrollTimer);
scrollTimer = window.setTimeout("scrollFinished()", 500);
}
function scrollFinished() {
document.body.style.backgroundColor = "red";
}
</script>
<div style="height:2000px;">
Scroll the page down. The page will turn red when the scrolling has finished.
</div>
</body>
</html>
Here's a more modern, Promise-based solution I found on a repo called scroll-into-view-if-needed
Instead of using addEventListener on the scroll event it uses requestAnimationFrame to watch for frames with no movement and resolves when there have been 20 frames without movement.
function waitForScrollEnd () {
let last_changed_frame = 0
let last_x = window.scrollX
let last_y = window.scrollY
return new Promise( resolve => {
function tick(frames) {
// We requestAnimationFrame either for 500 frames or until 20 frames with
// no change have been observed.
if (frames >= 500 || frames - last_changed_frame > 20) {
resolve()
} else {
if (window.scrollX != last_x || window.scrollY != last_y) {
last_changed_frame = frames
last_x = window.scrollX
last_y = window.scrollY
}
requestAnimationFrame(tick.bind(null, frames + 1))
}
}
tick(0)
})
}
With async/await and then
await waitForScrollEnd()
waitForScrollEnd().then(() => { /* Do things */ })
(function( $ ) {
$(function() {
var $output = $( "#output" ),
scrolling = "<span id='scrolling'>Scrolling</span>",
stopped = "<span id='stopped'>Stopped</span>";
$( window ).scroll(function() {
$output.html( scrolling );
clearTimeout( $.data( this, "scrollCheck" ) );
$.data( this, "scrollCheck", setTimeout(function() {
$output.html( stopped );
}, 250) );
});
});
})( jQuery );
=======>>>>
Working Example here
I did something like this:
var scrollEvents = (function(document, $){
var d = {
scrolling: false,
scrollDirection : 'none',
scrollTop: 0,
eventRegister: {
scroll: [],
scrollToTop: [],
scrollToBottom: [],
scrollStarted: [],
scrollStopped: [],
scrollToTopStarted: [],
scrollToBottomStarted: []
},
getScrollTop: function(){
return d.scrollTop;
},
setScrollTop: function(y){
d.scrollTop = y;
},
isScrolling: function(){
return d.scrolling;
},
setScrolling: function(bool){
var oldVal = d.isScrolling();
d.scrolling = bool;
if(bool){
d.executeCallbacks('scroll');
if(oldVal !== bool){
d.executeCallbacks('scrollStarted');
}
}else{
d.executeCallbacks('scrollStopped');
}
},
getScrollDirection : function(){
return d.scrollDirection;
},
setScrollDirection : function(direction){
var oldDirection = d.getScrollDirection();
d.scrollDirection = direction;
if(direction === 'UP'){
d.executeCallbacks('scrollToTop');
if(direction !== oldDirection){
d.executeCallbacks('scrollToTopStarted');
}
}else if(direction === 'DOWN'){
d.executeCallbacks('scrollToBottom');
if(direction !== oldDirection){
d.executeCallbacks('scrollToBottomStarted');
}
}
},
init : function(){
d.setScrollTop($(document).scrollTop());
var timer = null;
$(window).scroll(function(){
d.setScrolling(true);
var x = d.getScrollTop();
setTimeout(function(){
var y = $(document).scrollTop();
d.setScrollTop(y);
if(x > y){
d.setScrollDirection('UP');
}else{
d.setScrollDirection('DOWN');
}
}, 100);
if(timer !== 'undefined' && timer !== null){
clearTimeout(timer);
}
timer = setTimeout(function(){
d.setScrolling(false);
d.setScrollDirection('NONE');
}, 200);
});
},
registerEvents : function(eventName, callback){
if(typeof eventName !== 'undefined' && typeof callback === 'function' && typeof d.eventRegister[eventName] !== 'undefined'){
d.eventRegister[eventName].push(callback);
}
},
executeCallbacks: function(eventName){
var callabacks = d.eventRegister[eventName];
for(var k in callabacks){
if(callabacks.hasOwnProperty(k)){
callabacks[k](d.getScrollTop());
}
}
}
};
return d;
})(document, $);
the code is available here: documentScrollEvents
Minor update in your answer. Use mouseover and out function.
$(document).ready(function() {
function ticker() {
$('#ticker li:first').slideUp(function() {
$(this).appendTo($('#ticker')).slideDown();
});
}
var ticke= setInterval(function(){
ticker();
}, 3000);
$('#ticker li').mouseover(function() {
clearInterval(ticke);
}).mouseout(function() {
ticke= setInterval(function(){ ticker(); }, 3000);
});
});
DEMO
I was trying too add a display:block property for social icons that was previously hidden on scroll event and then again hide after 2seconds. But
I too had a same problem as my code for timeout after first scroll would start automatically and did not had reset timeout idea. As it didn't had proper reset function.But after I saw David's idea on this question I was able to reset timeout even if someone again scrolled before actually completing previous timeout.
problem code shown below before solving
$(window).scroll(function(){
setTimeout(function(){
$('.fixed-class').slideUp('slow');
},2000);
});
edited and working code with reset timer if next scroll occurs before 2s
var timer=null;
$(window).scroll(function(){
$('.fixed-class').css("display", "block");
if(timer !== null) {
clearTimeout(timer);
}
timer=setTimeout(function(){
$('.fixed-class').slideUp('slow');
},2000);
});
My working code will trigger a hidden division of class named 'fixed-class' to show in block on every scroll. From start of latest scroll the timer will count 2 sec and then again change the display from block to hidden.
For more precision you can also check the scroll position:
function onScrollEndOnce(callback, target = null) {
let timeout
let targetTop
const startPosition = Math.ceil(document.documentElement.scrollTop)
if (target) {
targetTop = Math.ceil(target.getBoundingClientRect().top + document.documentElement.scrollTop)
}
function finish(removeEventListener = true) {
if (removeEventListener) {
window.removeEventListener('scroll', onScroll)
}
callback()
}
function isScrollReached() {
const currentPosition = Math.ceil(document.documentElement.scrollTop)
if (targetTop == null) {
return false
} else if (targetTop >= startPosition) {
return currentPosition >= targetTop
} else {
return currentPosition <= targetTop
}
}
function onScroll() {
if (timeout) {
clearTimeout(timeout)
}
if (isScrollReached()) {
finish()
} else {
timeout = setTimeout(finish, 500)
}
}
if (isScrollReached()) {
finish(false)
} else {
window.addEventListener('scroll', onScroll)
}
}
Usage example:
const target = document.querySelector('#some-element')
onScrollEndOnce(() => console.log('scroll end'), target)
window.scrollTo({
top: Math.ceil(target.getBoundingClientRect().top + document.documentElement.scrollTop),
behavior: 'smooth',
})
Here's an answer that doesn't use any sort of timer, thus in my case predicted when the scrolling actually ended, and is not just paused for a bit.
function detectScrollEnd(element, onEndHandler) {
let scrolling = false;
element.addEventListener('mouseup', detect);
element.addEventListener('scroll', detect);
function detect(e) {
if (e.type === 'scroll') {
scrolling = true;
} else {
if (scrolling) {
scrolling = false;
onEndHandler?.();
}
}
}
}

Categories

Resources