Callback functions in JQuery event handlers

#1

https://www.codecademy.com/courses/learn-jquery/lessons/jquery-setup/exercises/event-handlers

About the event handlers;

First method
$(’#login’).on(‘click’, () => {

});

Second method
$(’#login’).on(‘click’, function() {

});

Third method
function gamma(){
… }
$(’#login’).on(‘click’, gamma);

Is " () => {…}" in method 1 short notation for “function() { …}” in method 2.

Also, do all three methods work the same in all cases without any exceptions? Are all three the same, or is there any difference in them?

$(this) in jQuery for mouseleave event
#2

First, all three examples have the same jQuery object in context. We can stipulate to that.

The first is okay as long as it doesn’t use $(this) or this.

The second is fine all around until we get to the third. That is the ideal way to write a callback function. A standalone, pure function that always gives a predictible response. x in, y out.

Or, click => response, that being the case.

Arrow functons are okay in callbacks as long as you use the event.target object for context, or the literal, eg., $('.nav-menu').

1 Like