[JavaScript] Getting the Position of the Mouse Pointer

There are a couple of ways to determine the coordinates of a mouse pointer. The position can be determined in a browser or in a screen.

1. window.event Object

The “window.event” object provides the following properties:

  • window.event.x / window.event.y: offset from the closest relatively positioned parent element
  • window.event.clientX / window.event.clientY : relative to the client area of the window, excluding window decorations and scroll bars
  • window.event.screenX / window.event.screenY : relative to the user’s screen
<div id="outer" style="position:relative;left:100px;top:100px;">
<div id="inner" style="width:400px;height:100px;background-color:Gray;">

Add the click event handler to the inner div.

document.getElementById("inner").onclick = onClicked;

function onClicked() {
  alert(window.event.x + ", " + window.event.y);
  alert(window.event.clientX + ", " + window.event.clientY);
  alert(window.event.screenX + ", " + window.event.screenY);

When you clicked anywhere in the inner div, 3 coordinates are all different. If there is no relative parent, “event.x” and “event.clientX” will return the same value.


2. Standard Event Object

The standard event object provides “clientX”, “clientY”, “screenX”, and “screenY” properties.

document.getElementById("inner").onclick = onClicked;

function onClicked(e) {
  alert(e.clientX + "," + e.clientY);
  alert(e.screenX + "," + e.screenY);


3. jQuery

jQuery provides the normalized “pageX” and “pageY” properties. The “clientX”, “clientY”, “screenX”, and “screenY” properties can be used but they are not normalized.

$(document).ready(function () {

function onClicked(e) {
  alert(e.pageX + ", , " + e.pageY);
  alert(e.screenX + "," + e.screenY);

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s