drewbenn drewbenn - 1 month ago 5
Javascript Question

What's the most lightweight way to add onclick() to hundreds of checkboxes?

I have a web page, primarily used by mobile users (about 80% of my users), with about 350

<input type="checkbox">
elements. When a checkbox is checked or unchecked, I want to call some javascript to save the state in local storage. When I created my page there were only about 100 elements so instead of making each element
<input type="checkbox" onclick="save();">
which seemed prone to typos or just plain forgetting to add the
onclick
, I added this to my
onload
function:

var input_elements = document.querySelectorAll("input[type='checkbox']");
for (var i = 0; i < input_elements.length; i++) {
input_elements[i].addEventListener("click", function() { save(this); });
}


which works great but adds a small penalty to page load times -- which is getting worse as I add elements, and I'm expecting to keep adding another 100-150 each year.

Is there a "better" way of doing this, both in terms of reducing load times (especially for mobile users with slower browsers) and preventing me from making dumb typos that break something for my users but are hard for me to spot?

Answer

You can add event handler on some common parent, for example some wrapper div or document if there's no wrapper parent. Search for event delegation mechanism to get more information about this pattern.

Comments