Mouse click event coordinatesQuestion: How do I determine where exactly the user clicked the mouse? Answer: To determine the exact x and y coordinates of a mouse event, use the following properties: event.screenX , event.screenY (the screen x and y coordinates)
event.clientX , event.clientY (coordinates relative to the top left corner of the browser window or frame).
What about cordinates relative to the top left corner of the page?
(This may or may not be the same as event.pageX , event.pageY
use clientX , clientY plus a scrolling correction:
event.clientX+document.body.scrollLeft ,
event.clientY+document.body.scrollTop
document.compatMode=='CSS1Compat' )
use clientX , clientY plus another scrolling correction:
event.clientX+document.documentElement.scrollLeft ,
event.clientY+document.documentElement.scrollTop
Example. Click anywhere on this page, and the click coordinates will be displayed in an alert box.
Here is the source code of the function handleEvent(e){ var evt = e ? e:window.event; var clickX=0, clickY=0; if ((evt.clientX || evt.clientY) && document.body && document.body.scrollLeft!=null) { clickX = evt.clientX + document.body.scrollLeft; clickY = evt.clientY + document.body.scrollTop; } if ((evt.clientX || evt.clientY) && document.compatMode=='CSS1Compat' && document.documentElement && document.documentElement.scrollLeft!=null) { clickX = evt.clientX + document.documentElement.scrollLeft; clickY = evt.clientY + document.documentElement.scrollTop; } if (evt.pageX || evt.pageY) { clickX = evt.pageX; clickY = evt.pageY; } alert (evt.type.toUpperCase() + ' mouse event:' +'\n pageX = ' + clickX +'\n pageY = ' + clickY +'\n clientX = ' + evt.clientX +'\n clientY = ' + evt.clientY +'\n screenX = ' + evt.screenX +'\n screenY = ' + evt.screenY ) return false; } |
Copyright © 1999-2011, JavaScripter.net.