Local Mouse Click
const RIGHT_BOUND = 200;
const measureEl = document.createElement('div');
Object.assign(measureEl.style, {
position: 'absolute',
left: 0,
top: 0,
zIndex: 999
});
function localPosition(e, element, w = 1, h = 1) {
// normalize desktop and mobile
const touches = e.touches;
let x;
let y;
if (touches != null && touches.length > 0) {
x = touches[0].clientX;
y = touches[0].clientY;
} else {
x = e.clientX;
y = e.clientY;
}
function location(width) {
let left = 0;
let right = RIGHT_BOUND;
let mid;
while (right - left > 0.0001) {
mid = (right + left) / 2;
measureEl.style[width ? 'width' : 'height'] = `${mid}%`;
measureEl.style[width ? 'height' : 'width'] = '100%';
element.appendChild(measureEl);
const el = document.elementFromPoint(x, y);
element.removeChild(measureEl);
if (el === measureEl) {
right = mid;
} else {
if (right === RIGHT_BOUND) {
return null;
}
left = mid;
}
}
return mid;
}
const left = location(1);
const top = location(0);
return left != null && top != null
? {
// percentage values
left,
top,
// pixel values
x: left * w * 0.01,
y: top * h * 0.01
}
: null;
}
const div = document.body.appendChild(document.createElement('div'));
div.innerHTML = 'click me';
Object.assign(div.style, {
postition: 'absolute',
transform: 'translate(20px, 20px) rotate(45deg) scale(0.8)',
width: '120px',
height: '90px',
color: 'white',
fontFamily: 'sans-serif',
background: 'gray'
});
document.addEventListener('touchstart', onClick);
document.addEventListener('mousedown', onClick);
function onClick(e) {
const info = localPosition(e, e.target, 120, 90);
console.log(info);
}
Find the local percentage and pixel values of the mouse/touch location.
I found this one on stackoverflow here by user 4esn0k.
This is an interesting alternative to semi-broken native browser solutions and custom matrix math 😉