Aleksandar • Vacić

iOS bits and pieces

innerHTML kills event handlers

This is probably old news to regular Javascript coders, but for me it was an ugly bite. I have renewed my interest in JS with the abundance of libraries springing up and started coding few solid client side interfaces in the office.

A certain interface was previously built in a hurry and HTML code was littered with plenty onclick="somefunction()" code. I re-factored all of that so that handlers were added on DOM.load; however, there was one nasty feature left in the code.

I had a table of 6 rows and button which that says “Add line”. Adding lines is easy: create the whole table row HTML on server, fetch that with XHR call and do tbody.innerHTML += sRow. Actually, this was the code I used for IE and as soon as this is done, all the previously set event handlers went missing. Like they never existed.

Bottom line: changing innerHTML property removes all late-bound event handlers and script on that piece of the page.

Solution was to get off my lazy fingers and type in proper DOM calls: insertRow and insertCell. Clean code and no browser branching. :)