Wednesday, February 27, 2008

Save yourself the effort of defining the same code for multiple javascript events

If you ever have a situation where you basically want to run the same code for a bunch of different events on an html element like an input, it's a pain in the ass to maintain if you change the logic and need to change all of the event parameters. I discovered you can directly call another event so you don't have to define and maintain the same code in multiple places. I realize you can do something very similar by using addEventListener, but I just thought this was kind of cool.

e.g.
// define the onchange event and call the same code for onmouseover, onmouseout, and onclick

// Now if you make changes to onchange, you don't need to copy those changes to the other events.


<input ... onchange="myFunctionDoYouLikeIt(this, 'valueadded', false, 0); compareSomeValues('placeholder', false, true, 'the google webz');"

onmouseover = "eval(this.onchange + '\;anonymous()\;');"

onmouseout = "eval(this.onchange + '\;anonymous()\;');"

onclick = "eval(this.onchange + '\;anonymous()\;');" />

No comments: