Anonymous functions for inline event handlers

Inline event handlers... remember them?! Yes, they've gone the way of the blink tag and Adobe Flash, but recently I used one while debugging and realised: "Hey! I have no idea how to get the event object in an inline even handler!" and, shortly after "In fact, no idea how to write an anonymous function in an inline event handler either!". So I set out to rectify the matters. After a bit of experimenting I came up with this:

onclick="(function(e){ alert(e); })(event)"

The event keyword gets magically passed into the context of the handler code - so you can write onclick="alert(event)". Though, I think you'd have to do alert( event || window.event ) for IE. tw;dt (too windows; did not test).

Next, if you want an anonymous function then you'll need to wrap it so it self-executes.

And finally, if you still want a handle to the this element, you'll need to pass that in too:

(function(e, obj){ alert(obj); })(event, this)