
Get the current position of the mouse from a JavaScript event
24/05/2020Lets look at how to get the current clientX and clientY position of the mouse pointer from a JavaScript 'mousemove' event.
Would you like to be able to open a modal, or a context menu? Maybe you are making a browser game, or simply adding a sparkly trail to your mouse. To do all of these things you need to know the current mouse position relative to the screen.
This simple problem was something I found myself googling fairly often when I was new to coding. I would usually include some catch like ‘get the current mouse position without using an event’. As far as I’m aware it isn’t possible to get the current mouse position without triggering a mouse event.
So how can we get the mouse position from a mouse event?
To get the current mouse position we are going to trigger a mouse event. In this case we will use ‘mousemove’ to log the current X and Y coordinates of the mouse to the console. For a more detailed list of mouse events you could have a read of this.
First we set up an event listener for our event:
document.addEventListener('mousemove', (event) => {
});
Now we can access our event object to get the client X and Y coordinates and log them to the console using string interpolation:
document.addEventListener('mousemove', (event) => {
console.log(`Mouse X: ${event.clientX}, Mouse Y: ${event.clientY}`);
});
As a result, if you now open your console you will see that every time you move the mouse there will be a log of the mouse coordinates ‘helpfully’ spammed all over your screen.
Lets look at how to get the current clientX and clientY position of the mouse pointer from a JavaScript 'mousemove' event.
Find out whether a JavaScript array contains single or multiple values by passing an array of values to includes() with the help of some() and every().
Would you like to match the closest number in an array using JavaScript? Find out how to achieve this using both reduce() and sort().
What are web components? Learn about web components, the shadow DOM, styling and lifecycle callbacks in this JavaScript tutorial series.
Learn how to use event listeners to detect and handle single and multiple keypress events in JavaScript. Add modifier keys to your application!
Using Bulma but don't know how to integrate it with Nuxt? I'll show you how to load Bulma into your Nuxt project with full control over variables.
It is very useful
your website blogs supports my rankings, thanks for sharing the posts!
Thanks, it’s great to see a modern tutorial using goodies like string interpolation.