ThomasReggi
ThomasReggi

Reputation: 59535

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.

Upvotes: 5

Views: 4097

Answers (2)

A. Wolff
A. Wolff

Reputation: 74410

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-

Upvotes: 11

Yauhen Vasileusky
Yauhen Vasileusky

Reputation: 685

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

Solution for firefox; for other browsers see @roasted solution

Upvotes: 0

Related Questions