admin管理员组

文章数量:1289623

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.

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.

Share Improve this question edited Apr 10, 2020 at 12:36 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked May 3, 2013 at 16:07 ThomasReggiThomasReggi 59.5k97 gold badges258 silver badges459 bronze badges 2
  • 1 $(window).scrollTop == 0 ??? jQuery's scrollTop function will never === 0, unless it's been shadowed or overwritten. Did you mean .scrollTop() === 0 ? – user1106925 Commented May 3, 2013 at 16:10
  • ...maybe when you get to 0, have the JS set it back to 1px. Could be it'll be a small enough change that it won't be too much of a visual distraction. jsfiddle/TKpsR – user1106925 Commented May 3, 2013 at 16:20
Add a ment  | 

2 Answers 2

Reset to default 11

Seems like what you are looking for:

http://jsfiddle/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

本文标签: javascriptScroll event doesn39t fire unless page movesStack Overflow