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 Introduction to jQuery DOM Manipulation Changing Styles

Alyssa Paulette
seal-mask
.a{fill-rule:evenodd;}techdegree
Alyssa Paulette
Full Stack JavaScript Techdegree Student 4,573 Points

Writing With Arrow Functions

I just tried writing the demo in this video using an arrow function, but that doesn't work for some reason.

$('.card').on('click', () => { $(this).toggleClass('selected'); });

I was able to successfully write the previous demo (posting a new pet) with an arrow function and it worked like a charm.

Did I do something wrong in this instance, or is there a conflict with arrow functions in jQuery?

1 Answer

andren
andren
28,558 Points

No, you didn't do anything wrong.

This is caused by the fact that in addition to having a shorter syntax arrow functions deal with binding of the this keyword differently from how a traditional function does it. You can read about how arrow functions deal with this here. But ultimately it's a somewhat complex topic as the this keyword in general is quite complex. Getting into a deep explanation of it is outside the scope of this post but there are tons of articles written about it if you are curious and want to research a bit for yourself.

Arrow functions deal with this in a way that makes more sense than the default way in quite a few instances, but there are situations like the one you have run into where it actually creates a problem rather than solves it. There are ways around this issue when using jQuery like using the currentTarget property of the event that is passed to the jQuery event listeners instead of using this like this:

// Assign the event that is passed in automatically to e
$('.card').on('click', (e) => {
  // then use the "currentTarget" property since that is essentially what "this" normally refers to
  $(e.currentTarget).toggleClass('selected');
});

But ultimately the simplest solution is to just use the regular function syntax when you use jQuery callbacks that make use of the this keyword.