Let’s say you’ve been tasked with the ominous task of taking a currently “working” checkout process written in a hodge-podge of Prototype, jQuery and plain jane JavaScript and adding click methods to all input and a elements. Now, let’s also say you can’t modify the current HTML/JavaScript at all (mostly because it’s all working and you don’t want to break it and it’s already indecipherable code). Now, let’s also say that the click method you are attaching needs to be hands down, no matter what, the FIRST method that executes when you click on the element.
Sure you can make your JavaScript the first JavaScript that gets run on the page (so that the dynamic bindings run first, and therefor (hopefully) execute first). But what about the HARD CODED html click methods? This little code snippet will go through and dynamically remove (and “cache” (save for later)) all of the hard-coded onclick functions, and then bind your live functions to do your new critical must trigger first event, and then call the original onclick method on the element.
Yes, this code is scary. Yes, I cried a little after I wrote it while curled up in a ball under my desk. Yes, I plan to submit it to thedailywtf.com. But sometimes you just have to do what you have to do. If you’re in a similar situation, this might just help you out a little. Prepare to throw up in your mouth, hold on to your hats, and dive in:
To understand this a little more, you might like to throw a whole bunch of console.log() statements in there to see the state of each variable at each step along the way. It’s actually kind of fascinating that this code even works.
The toString() on the onClick on the attr call actually returns:
"function onclick(e){doThing();}“
This is scary/cool/weird since the attribute it’s pulling is just
<input type="checkbox" onclick="doThing()" />
So I go through with the regex and strip off the “ onclick” leaving just an anonymous function: “function(e){doThing();}“
I then assign the anonymous function to the variable “clickMethod” thus creating a brand new function on the page called clickMethod, which can be triggered or called anywhere I want and even passed an event object!!!
*BARF* XP
Someone please tell me there’s a better way… If so, why not hook me up on FIXEE???











A few adjustments left in fixee:
http://fixee.org/paste/hi96794/#url=iejfl15
Ah, nice! Thanks Paul!
Thank you very much Chris for this code, I looked every every on the net and you code did the job, specially this:
jQuery.each(jQuery("div[onclick]"), function(){
//create an "onclickmethod" attribute and assign it the FUNCTION DEFINITION of the onclick method (in order to cache it for later use)
jQuery(this).attr("onclickmethod", jQuery(this).attr("onclick").toString());
//remove the onclick function bind
jQuery(this).removeAttr("onclick");
});
With this code I was able to remove de onclick attribute and then play with it’s value with jQuery.