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

Kamil Żogło
Kamil Żogło
10,114 Points

How about this approach "box.onclick=()=> alert('You clicked me!')"?

Is it recommended or not and why?

2 Answers

Steven Parker
Steven Parker
231,269 Points

You didn't provide a link to a course page, so I'm not sure what you are comparing this to. But this method seems fine for a very simple handler function like this one.

If you might have more than one handler, it would be preferable to use the "addEventListener" method to set up your handler(s). And if the function itself might get more involved, you might need to pass in the event object and/or use a conventional function (instead of an arrow function) to make references to "this" possible.

Steven Parker
Steven Parker
231,269 Points

Oh, I see now you are comparing this to using jQuery methods. Note that the jQuery methods do use "addEventListener" internally with conventional functions passing in the event handler, so you still get all the advantages of the wordier JavaScript methods but with a very compact syntax.

But still, for this particular simple example, I think both approaches are functionally equivalent.

Kamil Żogło
Kamil Żogło
10,114 Points

Again, thank you for making me aware of it.

Kamil Żogło
Kamil Żogło
10,114 Points

Thanks for your answer and yes, somehow I omited a link to a course. It's "jQuery vs. JavaScript"(https://teamtreehouse.com/library/jquery-vs-javascript).