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 Events Event Types

Arrow functions - jQuery

Why isn't it working?

$('.loc').hover( () => {
  $(this).html("<strong>Location:</strong> your House?!");
}, () => {
  $(this).html("<strong>Location:</strong> Treehouse Adoption Center");
});

And when I change the arrow function... Why is it working?

$('.loc').hover( function() {
  $(this).html("<strong>Location:</strong> your House?!");
}, function() {
  $(this).html("<strong>Location:</strong> Treehouse Adoption Center");
});  
Max Karacsony
Max Karacsony
23,928 Points

The difference is the this binding of the arrow function. By using an arrow function this is not the element you hover and so no html can be set on it. See this blog post: https://rainsoft.io/when-not-to-use-arrow-functions-in-javascript/ The second point describes your example.

2 Answers

Steven Parker
Steven Parker
231,269 Points

Arrow functions are not exact replacements for conventional functions.

There are several things conventional functions define for you that arrow functions do not, like arguments and as Max pointed out, this.

You can still use them as event handlers, but pass the event object to them and use its target property instead of this:

$('.loc').hover( e => {
  $(e.target).html("<strong>Location:</strong> your House?!");
}, e => {
  $(e.target).html("<strong>Location:</strong> Treehouse Adoption Center");
});

Max Karacsony Steven Parker Thanks