Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 432
ThomasReggi Avatar asked May 03 '13 16:05

ThomasReggi


1 Answers

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-

like image 140
A. Wolff Avatar answered Sep 19 '22 13:09

A. Wolff