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 Object-Oriented JavaScript (2015) Introduction to Methods Returning Values

Rachel Heneault
PLUS
Rachel Heneault
Courses Plus Student 12,155 Points

Method on the button

In the dom manipulation class they about event listeners. When you put the method on the button its like add event listener. I just wonder when do you choose to use the event listener method? This seems way more simplistic, and I like it. Is it just a personal preference?

var button = document.getElementById("button");

button.onclick = function() { var result = 1; printNumber(result); };

1 Answer

Steven Parker
Steven Parker
229,771 Points

Two differences come to mind:

  • the onclick property supports only one handler, addEventListener can be used to create multiple handlers
  • onclick attaches only a direct handler, with addEventListener the handler can be direct or delegated

So if you need only one direct handler, the onclick property is a handy shortcut.