3

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.

2 Answers 2

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.

3
  • After changing .mousewheel to .wheel, the alert always returns down, even when scrolling up.
    – Tim Lewis
    Commented Nov 25, 2015 at 16:45
  • @TimLewis I don't see this behaviour in this updated jsfiddle? jsfiddle.net/qexb1207/2
    – AGB
    Commented Nov 25, 2015 at 16:59
  • Hmm... What browser are you using? I notice down only in Firefox, but Chrome shows the correct direction.
    – Tim Lewis
    Commented Nov 25, 2015 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?

1
  • 1
    @AlanBuchanan You are right it doesn't need to. I edit
    – Nvan
    Commented Nov 25, 2015 at 17:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.