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 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
217,443 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.