Skip to content

Instantly share code, notes, and snippets.

@kirpalmakanga
Created May 11, 2020 20:39
Show Gist options
  • Save kirpalmakanga/f20056d52125e87c66271a4aca6bd78b to your computer and use it in GitHub Desktop.
Save kirpalmakanga/f20056d52125e87c66271a4aca6bd78b to your computer and use it in GitHub Desktop.
Get mouse position
const out = document.querySelector('output');
const plaindiv = document.querySelector('div');
const absdiv = document.querySelector('div.absolute');
const floatdiv = document.querySelector('div.float');
const getposition = ev => {
let x = ev.clientX;
let y = ev.clientY;
let pos = ev.target.getBoundingClientRect();
return {
x: x - pos.x|0,
y: y - pos.y|0
};
}
const showposition = ev => {
let {x:x,y:y} = getposition(ev);
out.innerText = `x: ${x} y: ${y}`;
};
plaindiv.addEventListener('mousemove', showposition);
absdiv.addEventListener('mousemove', showposition);
floatdiv.addEventListener('mousemove', showposition);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment