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

123
Visualizações
Event listener will stop working on an element after it changes (javascript only)

Please check the following executable example code ...

var inputform = document.getElementById('input-form');
var form = document.getElementById('message');
var input = document.getElementById('usermsg');

function change(value) {
  const form =`
    <form name="message" action="" id="message">
      <textarea  name="usermsg" id="usermsg"></textarea>
    </form>`;
  const div = `
    <div id="message">
      <div id="usermsg"></div>
    </div>`;
  var content = value == "div" ? div : form;

  inputform.innerHTML = content;
}

usermsg.addEventListener('keypress', function(e) {
  if (e.which == 13 && !e.shiftKey && input.value) {
    input.value = '';
  }
});
<div id="input-form">
  <form name="message" action="" id="message">
    <textarea  name="usermsg" id="usermsg"></textarea>
  </form>
</div>
<button onclick="change('div');">Press to div</button>
<button onclick="change('form');">Press to form</button>

I'am using this code to detect when a user clicks inside the element

usermsg.addEventListener('keypress', function(e) {
  if (e.which == 13 && !e.shiftKey && input.value) {
    input.value = '';
  }
});

It's supposed to be a listener but it will stop working if the element changes and even after, it changes back to its original form.

How can I prevent it from stop working with javascript only?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Okay, this is the answer:

inputform.addEventListener('keypress', function(e) {
  const tgt = e.target;
  if (tgt.id==="usermsg") {
     if (e.which == 13 && !e.shiftKey && tgt.value) {
       tgt.value = '';
     }
  }
});

Thank you guys.

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