This is a function that easily allows you to tie event handler functions to browser objects and avoid common pitfalls/bugs, using the minimum byte size for its functionality (far less than just one kilobyte!). "View source" to see/use it. Features include:
I hope you find it handy! (Try clicking the document and watching the title). It's free to use and distribute, as long as you retain the credit notice. If you like this and/or my other scripts, you're more than welcome to make a donation, too.
Copy and paste the code into your own project. You call the two main
functions, addEvent()
and removeEvent()
, with the
following parameters:
window
or
document
, to which your event will be attached.'load'
, 'click'
or
'mouseover'
).addEventListener()
.There's a few examples in the source of this page.
The functions you register are automatically passed the correct 'event'
object, alias window.event
in MSIE.
If any of the functions called explicitly returns false, the whole event
returns false, for compatibility with older scripts.
However, please use cancelEvent()
in your own scripts instead of
relying on this behaviour.
All functions are automatically removed when the page unloads in MSIE; you do not have to do anything special to work around memory leaks :).
The removeEvent()
function has the same parameters as
addEvent()
, it just works in reverse.
Good luck - Angus.