Mouse click event coordinates

JavaScript FAQ | Keyboard & Mouse Events FAQ  

Question: 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 clientX, clientY due to scrolling.) This page-based pair of coordinates is arguably the most useful - and, surprisingly, the trickiest to determine.

  • In most browsers except IE use: event.pageX, event.pageY
  • in Internet Explorer (backward-compatibility mode)
    use clientX, clientY plus a scrolling correction:
    event.clientX+document.body.scrollLeft,
    event.clientY+document.body.scrollTop
  • in Internet Explorer (standards mode, 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 onclick event handler used in this example:

    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.