Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - how to treat scroll as single event?

Tags:

jquery

scroll

When I bind function to scroll and scroll mousewheel once, the function runs seven or eight times. I want it to run only once when I scroll the mousewheel once, is this possible? I use this code:

$(document).ready(function () {
    $(window).bind('scroll', function() {
        alert("Scroll.");          
    }   
    });
});
like image 284
maciejjo Avatar asked Aug 09 '13 10:08

maciejjo


2 Answers

Try

$(document).ready(function () {
    var timerId;
    $(window).bind('scroll', function() {
        clearTimeout(timerId)
        timerId = setTimeout(function(){
            alert("Scroll.");          
        }, 200)
    });
});

Demo: Fiddle

like image 132
Arun P Johny Avatar answered Oct 21 '22 17:10

Arun P Johny


You can use throttle function from jQuery throttle debounce plugin.

$(function() {
    $(window).bind('scroll', $.throttle(100, function() {
        console.log('scroll');
    }));
});
like image 24
jcubic Avatar answered Oct 21 '22 16:10

jcubic