$(this) in jQuery for mouseleave event



In context to the question in the lesson whose link has been given:

I tried

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

instead of

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

Can anyone help me in understanding what is the mistake here? Why cannot I use ‘this’ variable here? Also, there is also only a single ‘div’ element with class nav-menu in the index.html.

In the first code, there is Dollar sign in front of (’.nav-menu) and (this). But I don’t know why it’s not visible in the preview.
Maybe that can also be a question :smile: , why some of the dollar signs are invisible in the preview. Maybe because they are used in the markup for some different purpose and here we are using HTML in the preview.


You can’t use this with arrow function syntax. If you do it this way, it works:

  $('.nav-menu').on('mouseleave', function() {
    $(this).slideUp(800); //I prefer the .slideUp to .hide

Hope this helps! Happy Coding!


You can read this for more information on this and arrow functions (no pun intended :laughing:):

1 Like

About the dollar sign and its significance…


is an alias for jQuery(); that is, both call the same function. The dollar sign is for convenience (less typing).

We invoke jQuery on an element node to create a jQuery object. Once created it will remain in memory with the variable reference we assign the object to.

$p = $('p')

The above has cached a collection of all the P-nodes (paragraph elements) in the HTML document. The dollar sign on the variable is meaningless to the program and is written to tell a reader that it is a jQuery object. Beyond that it is not required.

1 Like

Thanks a lot, @midlindner and @mtf :wink:

I have a somewhat similar doubt in callback functions, it would be great if you could help me there also.
I think it is also in relation to the use of ‘this’ variable as mentioned in this post.


A callback is a function from which you expect a response before moving further. That response will be the argument in the pending function call.

We can defer function calls by assigning only the function reference to an event handler, such as, .on(), or an iterator such as, .each(). Note that these are both functions that accept other functions as their arguments.


Here is the link to the doubt post about which I was talking: