6

I am trying this code to detect if the mouse direction is going up or down:

<html>  
    <head></head>
    <body>
        <div style="width: 500px; height: 500px; background: red;"></div>
    </body>
</html>

var mY = 0;
$('body').mousemove(function(e) {
    mY = e.pageY;
    if (e.pageY < mY) {
        console.log('From Bottom');
        return;

    } else {
        console.log('From Top');
    }

});

However this code doesn't work was i expect. Console log always show "from top"

Any idea ?

demo

daniel__
  • 11,633
  • 15
  • 64
  • 91

6 Answers6

11
var mY = 0;
$('body').mousemove(function(e) {

    // moving upward
    if (e.pageY < mY) {
        console.log('From Bottom');

    // moving downward
    } else {
        console.log('From Top');
    }

    // set new mY after doing test above
    mY = e.pageY;

});
maček
  • 76,434
  • 37
  • 167
  • 198
4

You are setting my = e.pageY before comparing it, which means the comparison will always be equal (and therefore false.)

try it like this

var mY = 0;
$('body').mousemove(function(e) {

    if (e.pageY < mY) {
        console.log('From Bottom');

    } else {
        console.log('From Top');
    }
    mY = e.pageY;

});
Karmic Coder
  • 17,569
  • 6
  • 32
  • 42
  • 1
    Be careful to remove the return statement here otherwise `mY` doesn't get set after upward mouse movement – maček Dec 09 '11 at 18:53
  • How is it that that only answer, that is currently listed, that won't work is the highest rated answer? – xbrady Dec 09 '11 at 19:01
1

e.pageY is always equal to mY because you set mY to e.pageY just before the if statement.

Anne
  • 26,765
  • 9
  • 65
  • 71
schnozzinkobenstein
  • 795
  • 1
  • 8
  • 14
0

if you use if/else it will always output 'Going Down', even though e.pageY == mY.

Use 2 if-statements instead!

var mY = 0;
$('body').mousemove(function(e) {

// moving upward
if (e.pageY < mY) {
    console.log('From Bottom');

// moving downward
}
if (e.pageY > mY) {
    console.log('From Top');
}

// set new mY after doing test above
mY = e.pageY;

});

just copied the code from macek and replaced the 'else' with an 'if(...)' btw

Norman
  • 785
  • 7
  • 27
0

The easiest way to do it. This way you can detect direction changes:

var tempMouseY=0;
$('body')
.mousemove(function(e) {
    moveY = -(tempMouseY-e.pageY);
    tempMouseY = e.pageY;
    if (moveY<0) {
        console.log('From Bottom');
    } else {
        console.log('From Top');
    }

 });
0

You needed to set your mY value after determining the direction (previously you were setting it prior - thus would always receive a specific result)

Code:

//Values starts at middle of page
var mY = $('window').height()/2;

//Compares position to mY and Outputs result to console
$('body').mousemove(function(e) {
    if (e.pageY < mY) {
        console.log('Going Up');   
    } 
    else {
        console.log('Going Down');
    }
    mY = e.pageY;
});

Working Example

Rion Williams
  • 74,820
  • 37
  • 200
  • 327