Search the Site

Sponsors

bottom corner

Get current mouse cursor position with Javascript

Sometimes I find it helpful to know where the user's mouse cursor is when a certain action takes place. For example, when a user mouses over a particular field label, I may wish to show a small explanation that provides instructions on how to populate the related field, and the message will show near the mouse cursor. The following script shows you how to get the user's mouse cursor position using only a few lines of code.

This page is filed under keyword(s): javascript.

The Javascript code below provides a sample of how the user's mouse cursor position, displayed as X- and Y-coordinates in relation to the top left corner of the page. In this example, I put the X- and Y-coordinate values in an input box, but you can tweak that to fit your needs.


<html>

<script type="text/javascript">
window.onload = init;
function init() {
	if (window.Event) {
	document.captureEvents(Event.MOUSEMOVE);
	}
	document.onmousemove = getCursorXY;
}

function getCursorXY(e) {
	document.getElementById('cursorX').value = (window.Event) ? e.pageX : event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
	document.getElementById('cursorY').value = (window.Event) ? e.pageY : event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
}
</script>

<body>

<input type="text" id="cursorX" size="3"> X-position of the mouse cursor
<br /><br />
<input type="text" id="cursorY" size="3"> Y-position of the mouse cursor

</body>
</html>

Below is a demo of the code listed above:

X-position of the mouse cursor

Y-position of the mouse cursor

Did you find this page useful? Please consider browsing other articles or subscribing to the RSS feed to keep up with latest.

This page is filed under keyword(s): javascript.
Author: C. Peter Chen
Last updated: 30 Jul 2008

bottom corner