0

I want to get current X and Y position of the cursor in the browser when I click or focus on some of the html elements. When I do this with onclick it worked. But with onfocus it didn't. Please see the examples below..

Working code

<html>
<head>
    <title>Untitled</title>
    <script type="text/javascript">
<!--
function findXCoord(evt) {
    if (evt.x)  return evt.x; 
    if (evt.pageX) return evt.pageX; 
}

function findYCoord(evt) {
    if (evt.y) return evt.y; 
    if (evt.pageY) return evt.pageY; 
}
//-->
</script>
</head>

<body>
<a onclick="alert('The x coordinate is: ' + findXCoord(event) + ' and the y coordinate is: ' + findYCoord(event));">Hi</a>
</body>

But when I change onclick to onfocus, It didn't show the x,y positions

(onclick="alert.... to onfocus="alert.......)

Sahal
  • 4,046
  • 15
  • 42
  • 68
  • I want to know how events works with 'onfocus' – Sahal Jun 15 '12 at 12:31
  • I know what you're asking. You said "But when I change onclick to onfocus, It didn't show the x,y positions" and I want to know what it **did** show. If something isn't working as you expect/want it to, you need to tell us what is currently happening so we can help you. – Anthony Grist Jun 15 '12 at 12:32
  • Also, I'm not even sure `focus` is a valid event for an `` tag. – Anthony Grist Jun 15 '12 at 12:33
  • When I use onfocus, It alert nothing and no error also. – Sahal Jun 15 '12 at 12:40
  • Dunno why Tim Down deleted his answer, I think it was correct. Focus is a [UI event](http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-UIEvent), there are no coordinates associated with it. You can get the event target (element) and get its coordinates though. Click is a [mouse event](http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-MouseEvent), and they do have coordinates. – RobG Jun 15 '12 at 14:00
  • Which browser are you testing with? – Tamil Jun 15 '12 at 14:44

2 Answers2

0

I think you forget to place href tag, though it won't return you co-ordinate except i.e. but it will fire the event http://jsbin.com/irexog/edit#preview working solution.

And ya onfocus is supported by the anchor.

you need to modify the event handling specific to browser like this

indiPy
  • 7,844
  • 3
  • 28
  • 39
  • I get like this, "The x coordinate is: undefined and the y coordinate is: undefined" – Sahal Jun 15 '12 at 12:41
  • The x coordinate is: undefined and the y coordinate is: undefined – Sahal Jun 15 '12 at 12:53
  • and did you tried using screenx/y? http://stackoverflow.com/questions/6073505/what-is-the-difference-between-screenx-y-clientx-y-and-pagex-y – indiPy Jun 15 '12 at 13:05
0

"onfocus" is not a mouse event, you can get mouse position only from mouse events.

You can use "onmouseover" if you really need it.

micnic
  • 10,915
  • 5
  • 44
  • 55