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

What is the difference between the `.onClick` function and the `addEventListner('click', () => {})`

Hi guys in the Object oriented JavaScript course, in the dice emulator app, I noticed Andrew Chalky used a button.onClick. Throughout the course we've always used the addEventListner to listen for an event. What is the difference between the two?

1 Answer

Steven Parker
Steven Parker
243,656 Points

As the name implies, "addEventListener" adds a new event listener each time you use it. You can have several on a single element.

The "onClick" element property allows you to provide the event handler callback to a single event listener internally attached to the element. It's not as versatile but it can be convenient for simple programs and for testing.