Scroll event doesn't fire unless page moves

I'm looking to get an event to fire when one scrolls "up" from $(window).scrollTop == 0 .

If you have the following code:

$(window).scroll(function(){
    console.log("scrolling")
});

On a page where the document < window height then that event never fires because $(window).scrollTop isn't changing, but this doesn't mean that there's no mouse scroll input. I want an event to fire on mouse scroll regardless if the page is moving or not.


Seems like what you are looking for:

http://jsfiddle.net/n8eVQ/

$(document).on('mousewheel DOMMouseScroll MozMousePixelScroll', function(event, delta) {
    console.log('mousewheel');
    //you could trigger window scroll handler
    $(window).triggerHandler('scroll');
});

Other way is to capture scroll event on modern browsers which support event capturing phase (IE>8). This can be used for any dynamic element. As jQuery doesn't implement capturing phase, you have to use javascript addEventListener() method. Here an example implementing logic to get scrolling direction for a textarea:

document.addEventListener('scroll', function (event) {
    var $elm = $(event.target);
    if ($elm.is('textarea')) { // or any other filtering condition
        // do some stuff
        var direction = $elm.scrollTop() > ($elm.data('scrollTop') || 0) ? "down" : "up";
        $elm.data('scrollTop', $elm.scrollTop());
        console.log('scrolling', direction);
    }
}, true);

-DEMO-


document.addEventListener('DOMMouseScroll', callbackFunction, false);

Solution for firefox; for other browsers see @roasted solution

链接地址: http://www.djcxy.com/p/95626.html

上一篇: PhoneGap移动应用程序在滚动时点击选择不正确的项目

下一篇: 除非页面移动,否则滚动事件不会触发