Get mouse position when triggering focus / blur events? - Javascript / jQuery

I use jquery to create an event:

$('input').focus(function(e){ console.log( e.pageX, e.pageY ); }); 

This doesn't seem to work ... any ideas on alternative ways to get the mouse position?


Help would be great, thanks :)

+6
source share
2 answers

You can only get mouse coordinates using mouse events. If you want to capture a mouse position, you can use the mousemove global event mousemove and save the coordinates in a set of variables, to which the focus function may later be available. Example:

 var pageX, pageY; //Declare these globally $(window).mousemove(function(e){ pagex = e.pageX; pageY = e.pageY; }); $('input').focus(function(){ console.log(pageX, pageY); // These variables have been defined by the global // mousemove event }); 
+8
source

If you are trying to get a position relative to an element, try something like this:

 $("input").focus(function(e){ var relativeX = e.pageX - this.offsetLeft; var relativeY = e.pageY - this.offsetTop; }); 
+2
source

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


All Articles