var CurrentMouseXPostion;
var CurrentMouseYPostion;
$(document).mousemove(function(event) {
CurrentMouseXPostion = event.pageX;
CurrentMouseYPostion = event.pageY;
});
Make an eventListener on the main object , in my case the document object, to get the mouse coords every frame and store them in global variables, and like that you can read mouse Y & Z whenever youlike , wherever you like.
You can't read mouse position in jQuery without using an event. Note firstly that the event.pageX
and event.pageY
properties exists on any event, so you could do:
$('#myEl').click(function(e) {
console.log(e.pageX);
});
Your other option is to use a closure to give your whole code access to a variable that is updated by a 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
I came across this, tot it would be nice to share...
What do you guys think?
$(document).ready(function() {
window.mousemove = function(e) {
p = $(e).position(); //remember $(e) - could be any html tag also..
left = e.left; //retrieving the left position of the div...
top = e.top; //get the top position of the div...
}
});
and boom, there we have it..
Moreover, mousemove
events are not triggered if you perform drag'n'drop over a browser window.
To track mouse coordinates during drag'n'drop you should attach handler for document.ondragover
event and use it's originalEvent property.
Example:
var globalDragOver = function (e)
{
var original = e.originalEvent;
if (original)
{
window.x = original.pageX;
window.y = original.pageY;
}
}
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);
}
In this way I'll always have the distance from the top saved in y and the distance from the left saved in x.
use window.event
- it contains last event
and as any event
contains pageX
, pageY
etc. Works for Chrome, Safari, IE but not FF.
Source: Stackoverflow.com