Is There A Way To Trigger Mousemove And Get Event.pageX, Event.pageY?
Solution 1:
You need to set pageX
and pageY
directly before triggering the event. To set these properties, make a jQuery.Event
object.
// create a jQuery event
e = $.Event('mousemove');
// set coordinates
e.pageX = 100;
e.pageY = 100;
// trigger event - must trigger on document
$(document).trigger(e);
Solution 2:
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.
Solution 3:
I'm not sure I fully understand the question. You can do:
$('.someClass').mousemove(function(event){
console.log(event.pageX);
console.log(event.pageY);
});
Now, whenever the mouse moves over someClass
, it will register the xy cordinates. Here's the jsfiddle to see it in action and the jquery documentation.
Solution 4:
You cannot move a mouse if that is what you're asking. But you could call a function with whatever context and arguments you want. E.g.:
function foobar(e)
{
this.className = 'whatever'; // this == element
}
someElement.onmousemove = foobar;
var obj = {whatever:'you want'};
foobar.call(someElement, obj); // calls foobar(obj) in context of someElement
Solution 5:
Think I know your problem. You're trying to query the mouse position programmatically. Perhaps you have code something like this:
$(document).one('mousemove.myModule', function (e) {
// e.pageY and e.pageX is undefined.
console.log('e.pageY: ' + e.pageY + ', e.pageX: ' + e.pageX); }
).trigger('mousemove.myModule');
Then you're absolutely right. The properties pageY and pageX on the event object won't be defined. Actually, there's a hole lot of stuff in the event object that won't be there, not just .pageY
and .pageX
. Could be some bug in jQuery. Anyways, just don't chain that call to trigger and trigger the event on $(window) instead. Don't ask me why it works though but for me it did:
$(document).one('mousemove.myModule', function (e) {
console.log('e.pageY: ' + e.pageY + ', e.pageX: ' + e.pageX); } );
// Now e.pageY and e.pageX will be defined!
$(window).trigger('mousemove.myModule');
Post a Comment for "Is There A Way To Trigger Mousemove And Get Event.pageX, Event.pageY?"