Friday, July 9, 2010

Find mouse pointer position using JavaScript

Sometimes we need to know the mouse cursor position to perform a certain action at that place.

For example, I need to show up a popup div near the mouse cursor position when user click over a particular field/link. You can get the mouse cursor position using following codes:

function getCursorPosition(e) {
    e = e || window.event;

    var pos = {x:0, y:0};

    if (e.pageX || e.pageY) {
        pos.x = e.pageX;
        pos.y = e.pageY;
    } else {
        var de = document.documentElement;
        var b = document.body;
        pos.x = e.clientX + (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
        pos.y = e.clientY + (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
    }

    return pos;
}