Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
8
rated 0 times [  9] [ 1]  / answers: 1 / hits: 28043  / 13 Years ago, fri, october 14, 2011, 12:00:00

So, like the question specifies, is there a way to trigger a mousemove event in jQuery which also sends the mouse coordinates to the event Object?


So far my code can trigger the mousemove using the .trigger(event) function but the event.pageX and event.pageY are undefined.


More From » jquery

 Answers
40

I don't believe it possible to get the mouse coordinates on demand via JavaScript / jQuery; however if you bind the position to a global var you can then access them at anytime throughout the document like this:



$(document).ready(function(){
$().mousemove(function(e){
window.xPos = e.pageX;
window.yPos = e.pageY;
});
});


for a less CPU intensive option, you can add a timeout, although you trade performance for a slight delay in knowing where the mouse is:



function getMousePosition(timeoutMilliSeconds) {
$(document).one(mousemove, function (event) {
window.xPos = event.pageX;
window.yPos = event.pageY;
setTimeout(getMousePosition( + timeoutMilliSeconds + ), timeoutMilliSeconds);
});
}
getMousePosition(100);


You should now be able to access the window.xPos and window.yPos from anywhere in the document using either solution without needing to trigger a faux event.


[#89606] Thursday, October 13, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kevonmoisesf

Total Points: 693
Total Questions: 101
Total Answers: 128

Location: Reunion
Member since Mon, Dec 28, 2020
3 Years ago
kevonmoisesf questions
Sat, Jan 23, 21, 00:00, 3 Years ago
Tue, Feb 18, 20, 00:00, 4 Years ago
Wed, Jun 12, 19, 00:00, 5 Years ago
;