Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine mouse position outside of events (using jQuery)?

I need to get a hold of the absolute mouse position / coordinates (X and Y) using (preferably) jQuery like in this tutorial but outside of any JavaScript event. Thank you.

like image 584
pbz Avatar asked Jul 15 '09 20:07

pbz


People also ask

How do I find my current mouse position?

To get the current mouse position we are going to trigger a mouse event. In this case we will use 'mousemove' to log the current X and Y coordinates of the mouse to the console.

How can get current cursor position in textbox using jQuery?

For exactly what you're after, there's the jQuery Caret (jCaret) plugin. For your code to get the position you could do something like this: $("#myTextInput"). bind("keydown keypress mousemove", function() { alert("Current position: " + $(this).

What is Mousemove Javascript?

Definition and Usage. The onmousemove event occurs when the pointer is moving while it is over an element.


2 Answers

Not possible. You can however use the same approach in the tutorial to store the position in a global variable and read it outside the event.

Like this:

jQuery(document).ready(function(){    $().mousemove(function(e){       window.mouseXPos = e.pageX;       window.mouseYPos = e.pageY;    });  }) 

You can now use window.mouseXPos and window.mouseYPos from anywhere.

like image 53
Chetan S Avatar answered Oct 02 '22 16:10

Chetan S


This started as a comment on Chetan Sastry's answer, but I realized it also might be worth posting as an answer:

I'd be careful about having a document-level, always-running mousemove event, even if you're only polling for cursor position. This is a lot of processing and can bog down any browser, particularly slower ones like IE.

A problem like this almost certainly raises the question of design decision: if you don't need to handle a mouse event to poll for the cursor position, do you really need the cursor position? Is there a better way to solve the problem you're trying to solve?

Edit: even in Safari 4, which is (understatement) very fast, that single mousemove event makes every interaction with that tutorial page noticeably choppy for me. Think about how that will affect users' perceptions of your site or application.

like image 40
eyelidlessness Avatar answered Oct 02 '22 17:10

eyelidlessness