Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

161
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda