How to get mouse position in jQuery without mouse events?

I want to get the current mouse position, but I do not want to use:

$(document).bind('mousemove',function(e){ $("#log").text("e.pageX: " + e.pageX + ", e.pageY: " + e.pageY); }); 

because I just need to get a position and process the information

+75
jquery position mouse
Dec 23 '10 at 9:00
source share
5 answers

I do not believe that there is a way to request the position of the mouse, but you can use the mousemove handler, which simply stores the information, so you can request the stored information.

 jQuery(function($) { var currentMousePos = { x: -1, y: -1 }; $(document).mousemove(function(event) { currentMousePos.x = event.pageX; currentMousePos.y = event.pageY; }); // ELSEWHERE, your code that needs to know the mouse position without an event if (currentMousePos.x < 10) { // .... } }); 

But almost all code, except setTimeout code, etc., is run in response to an event, and most events provide mouse position. So your code, which should know where the mouse probably already has access to this information ...

+130
Dec 23 2018-10-12T00:
source share

You cannot read mouse position in jQuery without using an event. Note that the properties event.pageX and event.pageY exist in any event, so you can do:

 $('#myEl').click(function(e) { console.log(e.pageX); }); 

Another option is to use closure to give your code access to a variable that is updated by the mousemove handler:

 var mouseX, mouseY; $(document).mousemove(function(e) { mouseX = e.pageX; mouseY = e.pageY; }).mouseover(); // call the handler immediately // do something with mouseX and mouseY 
+23
Dec 23 2018-10-12T00: 00Z
source share

I used this method:

 $(document).mousemove(function(e) { window.x = e.pageX; window.y = e.pageY; }); function show_popup(str) { $("#popup_content").html(str); $("#popup").fadeIn("fast"); $("#popup").css("top", y); $("#popup").css("left", x); } 

That way, I will always have the distance from the vertex stored at y, and the distance to the left of the save at x.

+9
Sep 27 '12 at 13:21
source share

In addition, mousemove events mousemove not fire if you execute drag'n'drop on a browser window. To track mouse coordinates during drag'n'drop, you must attach a handler for the document.ondragover event and use its originalEvent property.

Example:

 var globalDragOver = function (e) { var original = e.originalEvent; if (original) { window.x = original.pageX; window.y = original.pageY; } } 
+4
May 14 '13 at 13:17
source share

I came across this because it would be nice to share ... what you guys think.

 $(document).ready(function(){ window.mousemove = function(e){ p = $(e).position(); //remember $(e) - could be any html tag also.. left = e.left; //retieving the left position of the div... top = e.top; //get the top position of the div... } }); 

and an arrow, there we have it.

0
Aug 04 '15 at 11:56
source share



All Articles