Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

154
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!