views:

172

answers:

4

I'm wondering which is better for performance... I have a "web app" sort of thing. It has a lot of javascript. When a button is clicked, a hidden div becomes visible. This new div has 5 buttons. Which is better for performance:

1.) put the button click events in the html tag of each button like onClick="alert('hey');" 2.) Attach events to each button when the div is visible, and then remove the events when I hide the div containing the buttons?

The reason I ask is because I imagine the page might get bogged down if the events in the html tags are constantly there. I figure the page might be faster to only have those events when the user can see the buttons to click them.

Any help is great! Thanks!

+2  A: 

Unless those events are causing something to act as a link (which it seems Google learned to read) the put all this JS outside your HTML. It makes your code tidier and more maintainable. Can't be sure about performance.

Itay Moav
A: 

Keeping the event handlers registered when the elements are hidden will have no impact on performance, since the events won't fire.

Whether to use HTML attributes or the DOM to register event handlers isn't a matter of performance, it's a matter of clean design. You'll want to keep presentation as separate from behavior as possible. This means that if you use attributes, they should only bind the event to a handler (i.e. call a single function) rather than contain more complex code. That is, don't:

<button onclick="if ('red'==this.parent.style.backgroundColor) {...}">...</button>

do:

<button onclick="clickColorButton(event)">...</button>
outis
A: 

Thank you. I have it currently only calling a function. I think I'll keep it that way.

Gracias

Ah, not enough points for commenting, eh? Once you do (I believe it's 50 points), make sure that you respond to an answer by adding a comment, rather than posting a new answer (which isn't really an answer at all).
outis
+2  A: 

I would use event delegation.

This way you can freely add/remove any buttons without worrying about attaching events on each one of them. This approach is also more memory efficient, since you always have one single event handler instead of N ones directly on each button.

kangax