mishka
mishka

Reputation: 2057

Add ClickHandler to html class

I need to add ClickHandlers to many checkboxes (>4000), and it's doing for 40 sec. How can I add handler to all elements in html class?

now:

 ChckBoxHandler cbh = new ChckBoxHandler();
SimpleCheckBox.wrap(DOM.getElementById("chbid" + ID)).addClickHandler(cbh);

i want:

DOM.getElementsByClass("chkboxes").addClickHandler(cbh);

Upvotes: 0

Views: 162

Answers (2)

fernandohur
fernandohur

Reputation: 7174

I would take a simple solution:

Why don't you add a click handler to the parent widget (the html panel? or whatever panel you are using) and check for clicks.

Whenever a click is done you can then loop through your checkboxes and see which one has a checked state.

Upvotes: 1

Ibu
Ibu

Reputation: 43850

When you have a lot of elements in your page (4000 in your case), it is not a good idea to assigned an event to every single one of them. It will hurt performance. Instead you can use event delegation which consist of (in case of a click) assigning an event to the parent element and check which of the child element was clicked and run the code for it

Here is a very good tutorial of how it works by David Walsh, creator of jsfiddle.net.

How JavaScript Event Delegation Works

If you were to use jQuery there is a very simple method that takes care of that for you.

jQuery .live()

Upvotes: 0

Related Questions