I recently found myself working on a small script that needed to perform some actions upon submission of a form. We decided that this form may or may not have an existing event handlers. If I used the javascript form.onsubmit = function(e){ ... }
, it would overwrite the first event. We researched various ways of making sure both events fired and that it worked across all the browsers.
The key to making this work, without having to worry about attempting addEventListener or attachEvent, is simply to store the original event as an object, then call it when you want to. The following code will detail this easy procedure. This code is natural JS and needs no framework. Most importantly, its very easy to implement. It uses only 2 lines of extra code on top of your new event.
Solid Tip: Be sure to check to see if an original event exists before trying to call it by wrapping a conditional statement around it.
var oldHandler = myform.onsubmit; myform.onsubmit = function(e){ // do stuff. I could call this 1st or 2nd if I want if(oldhandler){ oldHandler(); } } |
Very easy and tested in Firefox, IE7, IE8, Safari, and Chrome. I really like the fact that I don’t need messy conditional code to check the browsers involved. You can choose to execute the original event before or after your new event. You could also add your own checks and not call one or the other based on the situation. Hope this helps. If it does, leave a comment!
Thanks,
Evan