Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

155
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda