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

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;
    }
};

Try preventDefault and/or stopPropagation.

Tags:

Javascript