2

I try to figure out which direction the user have "mousewheeled" using a binding on a mousewheel event for my element.

You can see in the following snippet, when mousewheeling your mouse over the grey rectangle, the event is triggered.

JSFiddle

HTML

<div class="rect"></div>
<div>
    Mousewheel event state : 
    <label class="event-state-mousewheel">Triggered !</label>
</div>

CSS

.rect {
    width : 200px;
    height : 200px;
    background-color : lightgrey;
}

.event-state-mousewheel {
    color : red;
    display : none;
}

JavaScript

$(function() {
    $('.rect').on('mousewheel', function(event) {
        $(".event-state-mousewheel").stop(true, false).fadeIn(250).fadeOut(250);
    });
});

PROBLEM

I cannot find a way to get the direction. I tryied to debug the object returned when the event is triggered, but it is way too big to debug since the amount of element in it is monstruous.

QUESTION

Is there a formula using these element (from the object returned) to get the mousewheel direction ? Or is there an event like $("#element").on("mousewheeltop") ?

NOTE

I want at possible not use any other external plugin, only JQuery.

Anwar
  • 4,162
  • 4
  • 41
  • 62

2 Answers2

5

The properties wheelDelta and detail are what you need, as below:

if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
    // Scroll up
}
else {
    // Scroll down
}

I've updated your jsfiddle with this code.

Also, note that the mousewheel event is deprecated and you should use wheel instead.

AGB
  • 2,378
  • 21
  • 37
  • After changing `.mousewheel` to `.wheel`, the alert always returns `down`, even when scrolling up. – Tim Lewis Nov 25 '15 at 16:45
  • @TimLewis I don't see this behaviour in this updated jsfiddle? https://jsfiddle.net/qexb1207/2/ – AGB Nov 25 '15 at 16:59
  • Hmm... What browser are you using? I notice `down` only in Firefox, but Chrome shows the correct direction. – Tim Lewis Nov 25 '15 at 17:08
0
​$(document).ready(function(){
    $('#foo').bind('mousewheel', function(e){
        if(e.originalEvent.wheelDelta > 0) {
            $(this).text('scrolling up !');
        }
        else{
            $(this).text('scrolling down !');
        }
    });
});

Watch this : Get mouse wheel events in jQuery?

Community
  • 1
  • 1
Nvan
  • 1,126
  • 16
  • 23