Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Object-Oriented JavaScript (2015) Introduction to Methods Returning Values

Craig Curtis
Craig Curtis
19,985 Points

What's the difference between using .onclick vs. .addEventListener('click', ...) ?

In Mr. Chalkley's jQuery Basics class, we learn that .click doesn't work on newly-created DOM events, while .on('click', ...) does.

Is this also the case here with .onclick vs. .addEventListener('click', ...)?

1 Answer

John Coolidge
John Coolidge
12,614 Points

I believe the main distinction between using .onclick and .addEventListener('click',...) is primarily one of utility. .addEventListener('click',...) will allow a single click to perform multiple functions (such as an interaction on the page and an AJAX request), while adding multiple .onclick methods to a single element will only allow the last .onclick assigned to it to run. .addEventListener is preferable in every case I can think of, even if only one function is going to run when the element is clicked (in case, for example, you wanted to expand your program later on; you'd need only add another addEventListener to the element rather than delete the .onclick and then add the two or more addEventListener methods).

I hope that helps. If not, please say so.

John