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

5 Replies to “Get current mouse cursor position with Javascript”

    1. Thanks for visiting Dev-Notes. The reason why you are seeing a higher Y value is because you probably have scrolled further down on the page. This Javascript returns absolute values counting from the very top-left corner of the entire page, not just of the current display area. In other words, if you had already scrolled, say, 500 pixels down, if your cursor is placed at 100px below the top of the current display, you will see “600” being returned.

    2. when you scroll down the page the position will change. though your screen can only show 1920 X 1080 the page is longer than 1080

Leave a Reply

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