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 AJAX Basics (retiring) AJAX and APIs Adding jQuery

Howard Goldstein
Howard Goldstein
9,399 Points

$(this) doesn't seem to be working

I'm having trouble getting the code here to work. Here's what I have.

$(document).ready(() => {
  $('button').click((event) => {
    $('button').removeClass('selected');
    $(this).addClass('selected');
  });               
});

The click is occuring and the removeClass function is working. (if I add perform $('button').addClass('selected') in the console, the buttons get selected and if I click then all the buttons get deselected), but the addClass isn't working. With a bit of troubleshooting it seems like $(this) is selecting the whole window and not the button.

Any ideas?

1 Answer

Steven Parker
Steven Parker
231,275 Points

One of the differences between "arrow" functions and conventional functions is that arrow functions do not establish a value for "this". But for handlers you can use "event.target" instead.

See the details on all the differences on the Arrow Funcitons documentation page.

Howard Goldstein
Howard Goldstein
9,399 Points

Got it. Really helpful. Thanks.