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 What is Traversal?

steven alston
steven alston
16,292 Points

$(this) is not working for me, but $(e.target) is?

$(this) is not working for me.

// Working
$('.spoiler').on('click', 'button', (e) => {
  console.log(e.target);

  $(e.target).prev().fadeIn(2000);                     

  $(e.target).hide();
});

// NOT Working!!
$('.spoiler').on('click', 'button', (e) => {
  console.log(e.target);

  $(this).prev().fadeIn(2000);                     

  $(this).hide();
});

2 Answers

Jeff Wong
Jeff Wong
10,166 Points

Hi Steven,

The issue is not with JQuery, but the arrow syntax itself. Basically the arrow function does not bind its own 'this', therefore you will have issues when you try to use 'this' in an arrow function expression. This blog https://dmitripavlutin.com/when-not-to-use-arrow-functions-in-javascript/ explains the issue with 'this' very well and take a look at no. 2, which is exactly the case here. You may think that 'this' in $('.spoiler').on('click', 'button', () => {}) points to the button where the click event was originated, but it actually refers to the window object and has no sense in your code.

Dale Severude
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Dale Severude
Full Stack JavaScript Techdegree Graduate 71,350 Points

You are correct. If you change your code to NOT use the ES2015 shortcut syntax it will work. Maybe jQuery is not current with ES2015 standards?

$('.spoiler').on('click', 'button', function(event) {
steven alston
steven alston
16,292 Points

I wonder what exactly is going on because most of the es2015 syntax works. Such as fat arrow functions, string interpolation, and template literals.