The Blog

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. :)

Banca

Banca

Beautiful and functional currency converter, supports just about any currency in the world.

Go Couch to 5k

Go Couch to 5k

The most popular starter running program in beautiful feature-rich app (GPS tracking, charts, detailed history etc)

Quickie to do

Quickie to do

The fastest short-term task-list / check-list app on the App Store. Really.

Guerrilla Cardio

Guerrilla Cardio

The most challenging high-impulse interval training in the world.

Run Mate

Run Mate

A versatile running coach app, with unlimited number of running programs. Perfect for casual runners.

Comments are closed.