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

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

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 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