1

What is the most "proper" way to bind a function to the click event of a class that has elements appended frequently?

I've read that using the "onclick" attribute on an element is not advised. If this is true, why? using "onclick" seems like the most straightforward method at this point.

If onclick is not used, then every time a new element is added to a class, you would have to unbind the click function for all members of the class, and then rebind it to avoid a double binding. With onclick, the problem is avoided completely.

So, to avoid double bindings, wouldn't this be easier?

onclick='somefunction(this)' 

instead of

$("#divid").click(function(){
  // do something
});

(where we would have to check for existing bindings on previously existing elements of the class)

Skeets
  • 3,311
  • 31
  • 52
  • IMHO, I think it's better to use .on, like on [this example](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements). So that dynamic elements would automatically have the corresponding events binded. But I'm really not updated with the latest implementations though. – KiiroSora09 Sep 29 '16 at 02:30
  • @KiiroSora09 - Thanks! that was exactly what I was looking for. If you want to write up an answer, I'll mark it as the correct answer. Otherwise, I'll answer this question myself. :) – Skeets Sep 29 '16 at 02:59
  • I posted it as an answer. Glad I could help :) – KiiroSora09 Sep 29 '16 at 03:20

1 Answers1

1

As per my comment above, this is possible by using .on(). See the answer for this question.

Community
  • 1
  • 1
KiiroSora09
  • 2,147
  • 15
  • 21