Excluding form fields from keypress handler assigned to body
I have a click handler on a web page assigned to the body element. I really want it to be active anywhere on the webpage. Or so I thought. Keypress events on text input forms will also trigger the body handler, which makes sense, but which I don't want.
Ideally, I would like the keypress handler to be assigned to the body element and to exclude only the input forms somehow. Is there a way to stop the event at the input level and prevent it from propagating to the body? (Or is this even the correct way to view HTML DOM events?)
+2
source to share
1 answer
It would be easier to just check which element triggered the event in your keypress handler and filter out the input elements:
document.onkeypress = function(evt) {
evt = evt || window.event;
var target = evt.target || evt.srcElement;
if ( !/INPUT|TEXTAREA|SELECT|BUTTON/.test(target.nodeName) ) {
// Do stuff
}
};
+6
source to share