asgasg asgasg - 3 years ago 80
Javascript Question

Best practice for event handling with JavaScript

What's the best practice for an event handler? I'm unsure if I should put the buttons with the function to trigger or if I should, like jQuery, wait for the button's on click event.

Usually you can do this:

$('.buttonOK').on('click', function(){

Or just add on the button the

Which should I prefer?

Answer Source

Short answer: definitely do it the first way. Event delegation is way more performant, but requires extra conditionals in your code, so it's basically a complexity versus performance tradeoff.

Longer Answer: For a small number of elements, adding individual event handlers works fine. However, as you add more and more event handlers, the browser's performance begins to degrade. The reason is that listening for events is memory intensive.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download