elementUnderPoint and elementsUnderPoint
document.addEventListener('mousemove', e => {
const el = document.elementFromPoint(e.clientX, e.clientY);
// msElementsFromPoint for old IE versions (which will thankfully be gone soon)
const els = document.elementsFromPoint(e.clientX, e.clientY);
if (el != null) {
console.log(
el.className,
els
)
el.style.border = '1px solid white';
}
});
// prevent scrolling
document.addEventListener('touchmove', e => e.preventDefault(), { passive: false });
// hardcoded for clarity
document.addEventListener('touchmove', e => {
const x = e.touches[0].clientX;
const y = e.touches[0].clientY;
const el = document.elementFromPoint(x, y);
const els = document.elementsFromPoint(x, y);
if (el != null) {
console.log(
el.className,
els
)
el.style.border = '1px solid white';
}
});
Object.assign(document.body.style, {
background: '#000',
margin: 0
});
// put some boxes on the page
for (let i = 0; i < 200; i++) {
const size = 10 + Math.random() * 80;
const halfSize = size / 2;
const x = Math.random() * 120 - 10;
const y = Math.random() * 120 - 10;
const rot = x * 3 + Math.random() * 90 - 45;
const col = `hsl(${rot}, 50%, 50%)`;
document.body.innerHTML += `
<div class="box box-${i}"
style="
transform: rotate(${rot}deg);
position: absolute;
background: ${col};
width: ${size}px;
height: ${size}px;
left: ${x}%;
top: ${y}%;
"></div>`;
}
Obtain the element or elements underneath the mouse or touch point. Open your dev console to see the results.