Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
90
rated 0 times [  92] [ 2]  / answers: 1 / hits: 37749  / 12 Years ago, wed, december 26, 2012, 12:00:00

If i want to bind an event on page scrolling i can use scroll();.



But how to fire when scroll() is ended up?



I would like to reproduce this:



   $(window).scroll(function(){
//do somenthing
});

$(window).scrollSTOPPED(function(){ //--> when i'm scrolling then i stop to scrolling (so NOT when page scrollbar is at the end top or bottom :)
//do somenthing else
});


any ideas?


More From » jquery

 Answers
114

tiny jquery way



$.fn.scrollStopped = function(callback) {
var that = this, $this = $(that);
$this.scroll(function(ev) {
clearTimeout($this.data('scrollTimeout'));
$this.data('scrollTimeout', setTimeout(callback.bind(that), 250, ev));
});
};


After 250 ms from the last scroll event, this will invoke the scrollStopped callback.



http://jsfiddle.net/wtRrV/256/



lodash (even smaller)



function onScrollStopped(domElement, callback) {
domElement.addEventListener('scroll', _.debounce(callback, 250));
}


http://jsfiddle.net/hotw1o2j/



pure js (technically the smallest)



function onScrollStopped(domElement, callback, timeout = 250) {
domElement.addEventListener('scroll', () => {
clearTimeout(callback.timeout);
callback.timeout = setTimeout(callback, timeout);
});
}


https://jsfiddle.net/kpsxdcv8/15/



strange fact



clearTimeout and clearInterval params don't have to be defined and can even be wrong types or even omitted.



http://jsfiddle.net/2w5zLwvx/


[#81228] Sunday, December 23, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
erinh

Total Points: 38
Total Questions: 100
Total Answers: 110

Location: Macau
Member since Mon, Nov 16, 2020
4 Years ago
;