Replacing HTML without memory leaks and redundant code


I’m building a JavaScript-based calendar for a client that will require me to replace the page’s HTML based on the user’s input. For example, if the user clicks on a particular date, then the month/week calendar will be replaced with the day calendar.

Needless to say, there are several event listeners involved. However, if I suddenly swap out the month calendar for a day calendar, does that mean that there are several event listeners in memory for elements that no longer exist? Or are those listeners destroyed when the elements are destroyed?

Basically my question is, every time I swap out the HTML, do I have to detach all of the old events too?


If you remove an element from the DOM, all event listeners are killed along with it.

This is sometimes the only way to get rid of an event listener, especially when using addEventListener and anonymous functions.

As long as you actually remove the elements from the DOM (via innerHTML or removeChild), then there is no need to faff about with removing event listeners.

It’s tidier to handle all the mouse events from a calendar in one place, rather than setting handlers on every possible target. If you have a table with 28-31 days visible in 42 table cells,
just handle ALL events from the table. You can always read the text value of the target or srcElement, to get the date, and you can change every cell without needing to reassign the handlers.

The same goes for div and span elements, but a table is an easy container for a month of days.

Thanks, Raffles. I am using innerHTML to replace the elements, so I guess I don’t have to worry about it too much.

mrhoo, I am just using one listener for the table, and then using the event’s target/srcElement property along with that target’s ID/href/class/other property to determine which action to take.