JavaScript to Get Mouse Event Coordinates

On this page we provide JavaScript that obtains the coordinates of mouse events in your document. You can use the function provided to determine the left and top position in the document of events such as mousemove, mouseover, click, or tap on a touch screen.

When a mouse event occurs, pageX and pageY properties of the event provide the coordinates of the event in the document. These properties are not supported in Internet Explorer prior to version nine. To support earlier versions of Internet Explorer, the event's clientX and clientY properties are used. The clientX and clientY properties provide the coordinates of the event in the viewport, so in order to provide the coordinates of the event in the document, you need to add the amount the document has been scrolled.

Function to Get Mouse Event Coordinates

demo results

The following function returns the left and top position of a mouse event in your document. Click this demo link to see the results displayed to the right.

function dw_getMouseLoc(e) {
    e = e || window.event; // for ie<9
    var x = 0, y = 0;
    var sOff; // for scroll offsets
    if ( typeof e.pageY === 'number' ) {
        x = e.pageX;
        y = e.pageY;
    } else {
        sOff = dw_getScrollOffsets();
        x = e.clientX + sOff.x;
        y = e.clientY + sOff.y;
    return { x: x, y: y};

function dw_getScrollOffsets() {
    var doc = document, w = window;
    var x, y, docEl;
    if ( typeof w.pageYOffset === 'number' ) {
        x = w.pageXOffset;
        y = w.pageYOffset;
    } else {
        docEl = (doc.compatMode && doc.compatMode === 'CSS1Compat')?
                doc.documentElement: doc.body;
        x = docEl.scrollLeft;
        y = docEl.scrollTop;
    return {x:x, y:y};

Function Explanation and Usage

First we make sure that the event object is available for earlier versions of Internet Explorer, then we check for the existence of the pageY property on the event object. If it is not a number then we get the scroll offsets using the dw_getScrollOffsets function described here and add those to the clientX and clientY properties.

The dw_getMouseLoc function returns an object containing x and y properties. The following demonstrates a basic example use of the function.

<p><a href="#" id="L1">click me</a></p>

<script type="text/javascript">
function check(e) {
    var loc = dw_getMouseLoc(e);

document.getElementById("L1").onclick = check;

The JavaScript Tooltip uses the mouseover or click event coordinates for positioning the tooltip.