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

Andrei Olar
Andrei Olar
20,827 Points

Rewrite JS using arrow function

Hello,

We have the following JS in this tutorial:

$(".loc").hover(
    function(){
      $(this).html("<strong>Location:</strong> Your house?!");
    },
    function(){
      $(this).html("<strong>Location:</strong> Treehouse Adoption Center");
    }
);

How should I rewrite this to make use of the arrow function? I've tried like this but it did not worked:

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

1 Answer

Steven Parker
Steven Parker
231,198 Points

Arrow functions don't bind "this".

But you could explicitly use the event object to obtain the target:

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

See the Arrow Functions page on MDN for more info about how arrow functions differ from ordinary functions.