
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.
Have you ever needed to get the difference between 2 numbers in JavaScript? This problem appears fairly silly at first because surely you just subtract the smallest number from the largest number; whatever is left is the difference. But what happens when you don’t know which number is the larger?
I’m going to show you 2 methods to solve this.
First we could use Math.abs(). Math.abs() will return the absolute value of the number passed to it.
const diff = (a, b) => {
return Math.abs(a - b);
}
console.log(diff(12, 17)); // Output: 5
In the example we subtract 17 from 12 (-5) and pass the value to Math.abs(). Math.abs() converts this to an absolute value and returns 5.
Another way to get the difference between 2 numbers, and perhaps a more purist way, is to check which number is larger and then subtract the smaller number from the larger. We can do this by writing our own function.
const diff = (a, b) => {
return (a > b) ? (a - b) : (b - a);
}
console.log(diff(12, 17)); // Output: 5
For those who don’t know, the above example uses a ternary operator. The condition is evaluated and on ‘true’ the first value is returned, on ‘false’ the second. In this case we check whether ‘a’ is greater than ‘b’ and then return either ‘(a – b)’ or ‘(b – a)’ depending on the result.
You could alternatively write this as an ‘if/else’ conditional statement and achieve the same result. The main benefit of this approach is that it is more ‘human readable’ and probably easier to follow for new developers beginning their journey.
const diff = (a, b) => {
if (a > b) {
return a - b;
} else {
return b - a;
}
}
The execution speeds of the 2 methods are practically the same.
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.