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 jQuery Basics Understanding jQuery Events and DOM Traversal Spoiler Revealer: Breaking it Down

Ioana Rusu
Ioana Rusu
9,599 Points

Different syntax - same result

Hi,

In this video, Treasure uses

$( "#target" ).click(function() { alert( "I've been clicked!" ); });

as an example on how to use the click event. I on the other hand use a different syntax and I get the same result. This is my way of using the method:

$("#target").on('click', function(){ //code here });

Can someone tell me if I am using it wrong or what is the difference ?

Thanks a lot in advance :)

2 Answers

andren
andren
28,558 Points

Your code is fine, and there is no difference between the code shown in the lecture and the one you wrote.

The documentation for the click method literally states:

This method is a shortcut for .on( "click", handler )

So click is just a convenience method that allows you to set up click listeners in a slightly more concise way. As you get farther into programming you'll experience more and more scenarios where there are multiple different ways of coding the exact same result. And that's normal, programming languages are usually designed to be quite flexible which leads there to be many ways of doing the same thing.

Gabbie Metheny
Gabbie Metheny
33,778 Points

I believe Treasure introduces click first, and gets to on later in the course as you begin talking about adding different, or multiple, event listeners. Like andren said, either one is correct, on is just more flexible.

Ioana Rusu
Ioana Rusu
9,599 Points

Hi Andren and Gabbie,

Thank you for your answers. My answer was indeed in a later video.

Many thanks for taking the time to reply :)

Happy coding