Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Difference between <button onclick='myFunction'> and adding event listener for click?

What's the difference between <button onclick='myFunction'> and adding a event listener? When should I use which method?

1 Answer

Steven Parker
Steven Parker
243,318 Points

You can add any number of event listeners, but an element has only one "onclick" property.

In most cases, you'll want to use event listeners but the "onclick" can be handy for testing or relatively trivial scripts where you're certain to need only one handler.