Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with mousewheel in jQuery

Tags:

jquery

I have the following code in the head-section:

<script type='text/javascript' src='/js/jquery.mousewheel.min.js'></script>

jQuery(function($) {
    $('#box').bind('mousewheel', function(event, delta) {
        var dir = delta > 0 ? 'Up' : 'Down',
        vel = Math.abs(delta);
        alert(dir + ' at a velocity of ' + vel);
        return false;
    });
});

In firefox 5 nothing happens at all. In Chrome 13 and IE 9 I get "Down at a velocity of NaN", no matter at which direction I scroll.

How can I fix this? What I want to do is to check if the user is scorlliing upwards, or if he´s scrolling downwards.

Thanks for your help!

like image 685
Daniel Avatar asked Dec 07 '22 19:12

Daniel


1 Answers

Not working either with new jQuery 2.0.1... well, it works but not as desired. This code only detect down movement (that means negative delta). I have tried this code and the result is always negative:

var num = 0;

$('#container').bind('mousewheel DOMMouseScroll',function(e, delta) {
    if(delta > 0) {
        $("#output").text(++num);
    } else {
        $("#output").text(--num);
    }

    e.stopPropagation();
    e.preventDefault();
});

The DOMMouseScroll is the same as mousewheel but for Firefox.

CORRECTION

I have found this new code in this post and now it's working in Chrome and Firefox (I have fixed it) with jQuery 2.0.1. The problem was that the delta value returned was undefined.

function extractDelta(e) {
    if (e.wheelDelta) {
        return e.wheelDelta;
    }

    if (e.originalEvent.detail) {
        return e.originalEvent.detail * -40;
    }

    if (e.originalEvent && e.originalEvent.wheelDelta) {
        return e.originalEvent.wheelDelta;
    }
}

var num = 0;

$('#container').bind('mousewheel DOMMouseScroll',function(e) {
    var d = extractDelta(e);

    if(d > 0) {
        $("#output").text(++num);
    } else {
        $("#output").text(--num);
    }

    e.stopPropagation();
    e.preventDefault();
});

Container and output are just two empty divs.

like image 177
Timbergus Avatar answered Dec 23 '22 13:12

Timbergus