Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

event.preventDefault() on keydown isn't working [duplicate]

Trying to capture the key presses on a Bootstrap Tab Panel menus, but it just bubbles up ignoring the preventDefault() placed on the tabs's keydown handler.

document.onkeydown = function(e) {
  console.log("document catched the keydown event");

};

$('body > div > ul > li > a').on("keydown",function (e) {
  console.log("handled by the child - stop bubbling please");
  e.preventDefault();

});

Example: http://www.bootply.com/xUlN0dLRaV

what am i missing here ?

like image 534
Stavm Avatar asked Mar 09 '17 12:03

Stavm


People also ask

How do I stop Keydown event?

I would create a flag or boolean variable called isKeyDown and set it to true when the key is down and false when the key is up. Then, in your keydown function, you can use an if conditional where if true, then skip otherwise run the function and set the value to true. On keyup, set the value to false.

What can I use instead of event preventDefault?

The following example demonstrates how invalid text input can be stopped from reaching the input field with preventDefault() . Nowadays, you should usually use native HTML form validation instead.

What does event preventDefault () do?

The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form. Clicking on a link, prevent the link from following the URL.

Does preventDefault stop bubbling?

preventDefault() Prevents the browsers default behaviour (such as opening a link), but does not stop the event from bubbling up the DOM.


1 Answers

Try e.stopPropagation()

e.stopPropagation() prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

$('body > div > ul > li > a').on("keydown",function (e) {
  console.log("handled by the child - stop bubbling please");
  e.preventDefault();
  e.stopPropagation();
});

Difference?

What's the difference between event.stopPropagation and event.preventDefault?

like image 133
daan.desmedt Avatar answered Oct 08 '22 08:10

daan.desmedt