In Javascript, how can you set the event handler of a DOM element to default behavior?
For example, suppose I set the onkeypress event of an input element:
elem.onkeypress = function() { alert("Key pressed!"); }
Later, how can I remove this event? Is it okay to simply set the onkeypress property to null? I tried that and it works, but I don’t know if it is the proper way to do this.
I’m pretty sure that the events will be
undefinedrather thannull, so you’d be better off setting back to that.It’s probably overkill, but to be more robust, you’re arguably better off keeping a reference to whatever used to be registered to the
onkeypressevent & reassign that (just in case some other script is trying to use it too). So: