I have some assets on my page that are near each other. When a user taps/holds somewhere when another element is nearby I want to open up an interaction to clarify which element they really want.
I can't make the assets further apart as I am following the design team. To make things more complicated, these elements are on a map so you are able to zoom and pan which is shifting the translate property. The library we're using for panning and zooming is Panzoom.
I have come across document.elementFromPoint() which might work to collect the elements. But wouldn't I have to loop through some sort of check for each pixel around the point? Something like 360deg * radius amount of checks? That seems super overboard to me.
The coordinates of the click event can be retrieved via the clientX and clientY properties.
You can loop through every element and calculate the distance between the click event's x and y properties and the element's x and y coordinates (achieved by getting the top and left properties after calling getBoundingClientRect()).
const targets = document.querySelectorAll('.target');
document.addEventListener('click', function(e) {
const x = e.clientX;
const y = e.clientY;
var minDist;
var minDistElem;
targets.forEach(e => {
const eRect = e.getBoundingClientRect();
const eX = eRect.left;
const eY = eRect.top;
var a = x - eX;
var b = y - eY;
var c = Math.sqrt(a * a + b * b); //distance
if (!minDist || c < minDist) {
minDist = c;
minDistElem = e;
}
e.classList.remove('closest');
})
minDistElem.classList.add('closest');
})
.target{height:20px;width:20px;border:2px solid;display:flex;align-items:center;justify-content:center;position:absolute}#target1{top:50px;left:100px}#target2{top:50px;left:200px}#target3{top:100px;left:100px}#target4{top:100px;left:200px}.closest{background-color:lightgreen}
<div class="target" id="target1">1</div>
<div class="target" id="target2">2</div>
<div class="target" id="target3">3</div>
<div class="target" id="target4">4</div>