Get current mouse cursor position with 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.


<script type="text/javascript">
window.onload = init;
function init() {
	if (window.Event) {
	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);


<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


Below is a demo of the code listed above:

X-position of the mouse cursor

Y-position of the mouse cursor

Leave a Reply

Your email address will not be published. Required fields are marked *