Determine mouse direction

I am trying to have this code detect that the direction of the mouse goes 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 does not work, I expect. The console log always shows "on top"

Any idea?

demo

+4
source share
6 answers
 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; }); 
+9
source

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

try it like

 var mY = 0; $('body').mousemove(function(e) { if (e.pageY < mY) { console.log('From Bottom'); } else { console.log('From Top'); } mY = e.pageY; }); 
+4
source

e.pageY always mY , since you set mY to e.pageY immediately before the if .

+1
source

You had to set the mY value after determining the direction (previously you set it earlier), so you would always get a certain 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

0
source

if you use if / else, it will always output "Going Down", although 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 'else' with 'if (...)' btw

0
source

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

 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
source

Source: https://habr.com/ru/post/1385587/


All Articles