[thelist] Avoiding DHTML memory leaks for good.

Keith Gaughan keith at digital-crew.com
Tue Mar 15 18:26:36 CST 2005

I thought I'd share this because it might be useful.

Last weekend I got sick and tired of DHTML memory leaks, so I knocked
together some code to handle it:


It's not hard to use. Just include it before any code that uses it. You
can register event handlers like so:

     EventManager.Add(obj, eventType, handler);

Where _obj_ is the object or id of the object you want to attach an
event handler to, _eventType_ is the name of the event to listen to 
(note to IE users: omit the initial "on" in the name; it should be
"mousemove" or "click", not "onmousemove" or "onclick"), and _handler_
is the function to be called when the event is triggered.

Here's a simple example. Say you have a button whose id is "foo", and
you want to be told when it's clicked, to do so you can do:

     var elem = document.getElementById("foo");
     EventManager.Add(elem, "click", function()
         alert("Button 'foo' clicked!");


     EventManager.Add("foo", "click", function()
         alert("Button 'foo' clicked!");

Easy peasy.

When the browser unloads the page, EventManager automagically cleans up
any event handlers registered with it. This fixes some severe memory
leakage problems you can get with IE, and to a lesser extent with other

It's free to use. Just keep the copyright at the top of the file and
don't pass it off as your own work. If you make extensive use of it in
anything, some attribution would be nice, though not essential, and it'd
also be cool if I could see where it's used so I can have my ego stroked
a bit. :-)


More information about the thelist mailing list