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

161
Visualizações
Stop propagation of escape event from confirm() dialog

I have a dismissable form where I need to show confirmation on dismissing before closing it.

const button = document.getElementsByTagName('button')[0];
const textarea = document.getElementsByTagName('textarea')[0];

button.addEventListener('click', () => {
  button.classList.add('hidden');
  textarea.classList.remove('hidden');
  textarea.focus();
});

textarea.addEventListener('keyup', (e) => {
  if (e.key !== 'Escape') return;
  if (!confirm('Are you sure you want to close ?')) return;
  button.classList.remove('hidden');
  textarea.classList.add('hidden');
});
.hidden {
  display: none;
}
<button type="button">Edit</button>
<textarea class="hidden"></textarea>

The form (represented by the textarea) can be closed with the escape key.
But this escape key also controls the confirmation dialog, and it propagates to my handler.
So it closes the confirm dialog, then reopens it.

Is there a way to prevent the propagation of the escape event from the confirm dialog to the textarea ?

Fiddle

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

0

I added a flag that will store the fact you actually exited the dialog so that when the event gets fired again the next time it will use the flag to return from the handler:

const button = document.getElementsByTagName('button')[0];
const textarea = document.getElementsByTagName('textarea')[0];

button.addEventListener('click', () => {
  button.classList.add('hidden');
  textarea.classList.remove('hidden');
  textarea.focus();
});

let dialogWasRefused = false;

textarea.addEventListener('keyup', (e) => {  

  if(dialogWasRefused){
    dialogWasRefused = false;
    return;  
  } 
  
  if (e.key !== 'Escape') return;  
  if (!confirm('Are you sure you want to close (real message not from the fiddle platform) ?')) {
    dialogWasRefused = true;
    return;
  }
  button.classList.remove('hidden');
  textarea.classList.add('hidden');  
});
.hidden {
  display: none;
}
<button type="button">Edit</button>
<textarea class="hidden"></textarea>

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