0

I am practicing some jQuery and have some issue that return the expected result. As I understand it, to target the selected element inside an event handler, we can pass the event to the callback function and use event.currentTarget instead.

So this:

$('.nav-menu').on('mouseleave', ()=>{
  $('.nav-menu').hide();
});

Would become this:

$('.nav-menu').on('mouseleave', (event)=>{
  $(event.currentTarget).hide();
});

If I understand this link (W3Schools) correct, the same thing could be achieved using $('this'):

$('.nav-menu').on('mouseleave', ()=>{
  $(this).hide();
});

In this last case, the callback function does not need to be passed the event as parameter. It's also shorter, so that's cool :)

But it doesn't work. I'm not sure why. The first 2 solutions work fine.

Advice anyone? Thanks!

TVBZ
  • 564
  • 1
  • 4
  • 15
  • 2
    This difference is due to your use of arrow functions as they maintain the outer scope. See the duplicate for more information. Also, please don't use W3Schools as a reference. Their articles are often outdated and sometimes just plain wrong. MDN is far more comprehensive and accurate: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions – Rory McCrossan Mar 13 '19 at 12:57
  • In the last one, if you change `()=>` to `function()` it will work because of how the arrow functions work. – Blue Eyed Behemoth Mar 13 '19 at 12:59
  • @RoryMcCrossan Thanks for the tips. It was my first question to stackoverflow. I will refer to MDN from now on. – TVBZ Mar 13 '19 at 13:20
  • @BlueEyedBehemoth Hah.. Many thanks. That works. :) – TVBZ Mar 13 '19 at 13:20
  • No problem, glad I could help. – Blue Eyed Behemoth Mar 13 '19 at 13:33

0 Answers0