13

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 ?

Stavm
  • 7,833
  • 5
  • 44
  • 68

2 Answers2

24

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?

Community
  • 1
  • 1
daan.desmedt
  • 3,752
  • 1
  • 19
  • 33
  • 1
    When you determine a question is a duplicate, rather than answering it, post a comment saying it's a duplicate so people can close it correctly. (And of course, in about 1400 points of rep, you'll be able to cast close votes directly.) – T.J. Crowder Mar 09 '17 at 13:05
0

Besides e.preventDefault you have to also use e.stopPropagation() to prevent event bubling up. In your case you can also return false from event handler which do both:

$('body > div > ul > li > a').on("keydown",function (e) {
  console.log("handled by the child - stop bubbling please");
  return false;
});
Bartek Fryzowicz
  • 6,464
  • 18
  • 27