Alex
Alex

Reputation: 35098

Why is canceling a key-down not working if I display an alert

I want to cancel a key down, which works when I do not display an alert.

If I display one, it does not work.

JS Fiddle is here: https://jsfiddle.net/phbmvg8y/1/

Why is that?

<body>
  Without alert it works - with alert it does not
  <input type="text" class="noalert" value="without alert">
  <input type="text" class="alert" value="with alert">
  <div class="alert" contenteditable=true>alert</div>
  <div class="noalert" contenteditable=true>noalert</div>
</body>

$('.alert').on('keydown', function(event) {
  event.preventDefault();
  event.stopPropagation();
  window.alert('keydown intercepted');
  return false;
});

$('.noalert').on('keydown', function(event) {
  event.preventDefault();
  event.stopPropagation();
  return false;
});

How can it be fixed?

Upvotes: 2

Views: 204

Answers (2)

Akshay Arora
Akshay Arora

Reputation: 1945

It is because of how keydown works. From jQuery docs:

The keydown event is sent to an element when the user first presses a key on the keyboard. It can be attached to any element, but the event is only sent to the element that has the focus

When you display the alert, the element loses the focus, and the focus is transferred to the alert box. That is why you get a differential behaviour for the two cases you mentioned.

Upvotes: 3

Rory McCrossan
Rory McCrossan

Reputation: 337627

It's to do with the order that the user's action is trapped and the event is raised. To do what you require use keypress instead:

$('.alert').on('keypress', function(event) {
    event.preventDefault();
    event.stopPropagation();
    window.alert('keypress intercepted');
    return false;
});

Updated fiddle

Upvotes: 1

Related Questions