How to Get Mouse Coordinates with Javascript !!!

Yesterday while working on a script and I wanted to know the cursor X, Y coordinates. Suprisingly I forgot how to get the X and Y coordinates of mouse. After thinking for some time, its strike that everything related to the current state is stored in events. So How to get the X and Y positions.

-capture mousemove event and list down all its properites

This is how I find X and Y coordinates

<html>
<head>
<title>Get Mouse Coordinates</title>
<script language=”javascript”>
var divObj;

/**
* capture mousemove event, this statement will cause browser to
* call getMouseCoordites function each time mouse moves
*/
document.onmousemove=getMouseCoordinates;

/**
*identify which event is supported
* Based on that collect pageX and pageY properties of the event object
* pageX and pageY gets the X and Y cursor coordinates
*/
function getMouseCoordinates(event)
{
ev = event || window.event;
divObj.innerHTML = “Mouse X:”+ev.pageX + ” Mouse Y:”+ev.pageY;
}

//assign the mouseCoord Object to divObj
function loadDiv()
{
divObj = document.getElementById(“mouseCoord”);
}
</script>
</head>

<body onLoad=”loadDiv()”>
<div id=”mouseCoord”>Mouse Coordinates position will be displayed here.
</div>
</body>
</html>

Script works well with Mozilla, For IE need to do further modification in finding the exact position by calculating different properties value.

Advertisements

3 Responses to How to Get Mouse Coordinates with Javascript !!!

  1. Dhanasekar R says:

    Test

    function unLoadFnc(evt)
    {
    var e = (window.event) ? window.event : evt;
    alert(e.clientX);
    }

    Sample Html.

  2. Mouse says:

    Mouse

    yeah thats what I ment, i didnt remember the spelling but i did remember the meaning of the Mouse

  3. Shadmehr Vadoodi says:

    Thank you So much for this script

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: