'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



Solution 1:[1]

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>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Diego De Vita