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 ?
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.
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.
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.
preventDefault() Prevents the browsers default behaviour (such as opening a link), but does not stop the event from bubbling up the DOM.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With