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

151
Vistas
Element event listener affects other element

I'm adding divs on user clicks. If the user clicks an exciting div I want it to change color. Yet somehow the affected div is always the last appended one. How can I make the pressed div be the one who is affected?

document.addEventListener('click', e =>{
    el=document.createElement('div')
    document.body.appendChild(el)
    el.style.left = e.clientX-25 + 'px'
    el.style.top = e.clientY-25 + 'px'
    el.addEventListener('click', e =>{
      el.style.backgroundColor = 'green'
    })
})
div {
    width:50px;
    height:50px;
    background-color:blue;
    border: 1px solid black;
    position:absolute;
}
<html>
    <body>
        click to make two different squres. then click again on the first squre you created.
    </body>
</html>

try running this code, click to create two squres, then click again on your first squre. Why whould the second one change color?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You are implicitly creating a global variable named el here:

el=document.createElement('div')

When you click on a square, the click listener will run and do:

el.style.backgroundColor = 'green'

This will look up what el currently references and change its style. But el is global, and it gets reassigned every time a click occurs (and a square is created). So, any time you click any of the squares, the last square created will always be the one that gets its style changed.

Declare the el so that it's only scoped to the function, rather than global.

document.addEventListener('click', e => {
  const el = document.createElement('div')
  document.body.appendChild(el)
  el.style.left = e.clientX - 25 + 'px'
  el.style.top = e.clientY - 25 + 'px'
  el.addEventListener('click', e => {
    el.style.backgroundColor = 'green'
  })
})
div {
  width: 50px;
  height: 50px;
  background-color: blue;
  border: 1px solid black;
  position: absolute;
}
<html>

<body>
  click to make two different squres. then click again on the first squre you created.
</body>

</html>

I'd highly recommend using ESLint and its no-undef rule to help yourself avoid making these sorts of mistakes.

You also might want to not create a square if you're clicking on an existing square - instead, only change the existing square's color. If that's what you want, then keep the event from propagating.

document.addEventListener('click', e => {
  const el = document.createElement('div')
  document.body.appendChild(el)
  el.style.left = e.clientX - 25 + 'px'
  el.style.top = e.clientY - 25 + 'px'
  el.addEventListener('click', e => {
    // don't let the event bubble up to the click listener above
    e.stopPropagation();
    el.style.backgroundColor = 'green'
  })
})
div {
  width: 50px;
  height: 50px;
  background-color: blue;
  border: 1px solid black;
  position: absolute;
}
<html>

<body>
  click to make two different squres. then click again on the first squre you created.
</body>

</html>

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