Ask coding questions

← Back to all posts
How do you get the Mouse X and Y in JS?
wcacoding (3)

How do you get the Mouse's X and Y position using JS?

Answered by eankeen (2053) [earned 5 cycles]
View Answer
eankeen (2053)

Hey! :P
So I would do it a bit differently than @TheDrone7. Here, I create an event listener on the whole document for mousemove. So, whenever the user moves his or her mouse, the function handleMouseMove is fired.

The first argument of the function is an event. You can read more about MouseEvents here.

So I would recommend using something like this

document.addEventListener("mousemove", handleMouseMove)

function handleMouseMove(event) {
        // console.log(event);

        xCoordinate = event.clientX;
        yCoordinate = event.clientY;

You might be wondering if you can attach the listener on other things, besides just mousemove. Yah you can! You can actually take a look at the whole list here ;)

I actually make a repl, if you want to check it out. :P

TheDrone7 (1776)

@eankeen firstly, I did the same thing with different coding style.
Secondly, you might was keep those last two lines out of the code block.

TheDrone7 (1776)

Mouse position in JS isn't normally available at all times, you can get it when an event like mousemove or click is fired.

Here is how you would get it in mousemove event

    document.onmousemove = handleMouseMove;
    function handleMouseMove(event) {
        var eventDoc, doc, body;

        event = event || window.event; // IE-ism

        // If pageX/Y aren't available and clientX/Y are,
        // calculate pageX/Y - logic taken from jQuery.
        // (This is to support old IE)
        if (event.pageX == null && event.clientX != null) {
            eventDoc = ( && || document;
            doc = eventDoc.documentElement;
            body = eventDoc.body;

            event.pageX = event.clientX +
              (doc && doc.scrollLeft || body && body.scrollLeft || 0) -
              (doc && doc.clientLeft || body && body.clientLeft || 0);
            event.pageY = event.clientY +
              (doc && doc.scrollTop  || body && body.scrollTop  || 0) -
              (doc && doc.clientTop  || body && body.clientTop  || 0 );

        // Use event.pageX / event.pageY here which are the x and y co-ordinates of the mouse pointer.

Please upvote and Mark this as the correct answer if it is what you were looking for.