Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

160
Views
Is There A Way To Select Elements Near a Click Event?

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!