Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I consume a key event in javascript, so that it doesn't propagate?

Tags:

javascript

How do I consume a key event in javascript, so that it doesn't propagate?

like image 340
The Student Avatar asked Dec 17 '10 12:12

The Student


People also ask

How do you stop event propagation?

To stop an event from further propagation in the capturing and bubbling phases, you call the Event. stopPropation() method in the event handler. Note that the event. stopPropagation() method doesn't stop any default behaviors of the element e.g., link click, checkbox checked.

Which method can be used to stop propagation of an event in Javascript?

stopPropagation() The stopPropagation() method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases.

Which event can be used to stop event propagation in react?

stopPropagation() will stop event from propagating to the window.

How do you stop event propagation with inline onclick attribute?

Use event. stopPropagation(). Show activity on this post.


2 Answers

If you don't want the event to propagate and you're not using jQuery (or another library that wraps native browser events), you need to use the event's stopPropagation() method in most browsers and its cancelBubble property in IE. Don't bother with return false or preventDefault(): those only affect whether the native browser action happens for the event and have nothing to do with propagation.

For example:

document.onkeypress = function(evt) {
    evt = evt || window.event;
    if (typeof evt.stopPropagation != "undefined") {
        evt.stopPropagation();
    } else {
        evt.cancelBubble = true;
    }
};
like image 87
Tim Down Avatar answered Sep 21 '22 21:09

Tim Down


Try preventDefault and/or stopPropagation.

like image 27
Douglas Avatar answered Sep 20 '22 21:09

Douglas