8

I'm using jQuery to capture an event:

$('input').focus(function(e){

    console.log( e.pageX, e.pageY );

});

This doesn't seem to work... any ideas on alternative ways to getting the mouse position?


Help would be great.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
RadiantHex
  • 24,907
  • 47
  • 148
  • 244
  • I think you can only get the mouse coordinates on events that use the mouse -- click, dblclick, etc. It would be meaningless to get the mouse coordinates if a user focuses on your input by tabbing with the keyboard. – Blazemonger Nov 02 '11 at 17:34

2 Answers2

8

You can only get mouse coordinates using mouse events. If you want to capture the position of the mouse, you can use a global mousemove event listener, and store the coordinates in a set of variables, which can later be accessed by the focus function. Example:

var pageX, pageY; //Declare these globally
$(window).mousemove(function(e){
    pagex = e.pageX;
    pageY = e.pageY;
});

$('input').focus(function(){
    console.log(pageX, pageY); // These variables have been defined by the global
                               //  mousemove event
});
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • This is the only way to do it, afaik – Ruan Mendes Nov 02 '11 at 17:36
  • Did they mean any [mouse] event here?? ".pageX and .pageY can be read off of any event, not just .mousemove(). For example, perhaps you want to know exactly where a user clicked inside a particular div: Here's an example where we listen for a click event inside a particular div called #special." http://docs.jquery.com/Tutorials:Mouse_Position – jbabey Nov 02 '11 at 17:37
  • @jbabey A click is a mouse event. `focus` is not a mouse event. – Rob W Nov 02 '11 at 17:39
  • @RobW right I understand and I agree with you - it's just strange that the site I linked above says "any event" instead of "any mouse event" – jbabey Nov 02 '11 at 17:40
  • @Andy I originally wanted to use `x` and `y` too. Then, I thought "It is very likely that x or y are already defined within a function, causing conflicts." Hence, I decided to use the descriptive yet compact `pageX` and `pageY` variable names. – Rob W Nov 02 '11 at 17:43
  • @RobW I'm notorious among my coworkers for my descriptive variable names :) – Andy Nov 02 '11 at 18:01
2

If you're trying to get the position relative to the element, try something like this instead:

$("input").focus(function(e){
    var relativeX = e.pageX - this.offsetLeft;
    var relativeY = e.pageY - this.offsetTop;
});
James Johnson
  • 45,496
  • 8
  • 73
  • 110