Reputation: 1009
I'm passing the click event into my function but doesn't seem to be working?
$('body').on("click", youclick(event));
function youclick(e){
console.log("testing");
e.stopPropagation();
}
Upvotes: 0
Views: 72
Reputation: 2670
As @Rajaprabhu suggested. When you are using a callback function(youclick(e)), the callback argument(youclick) is passed as the function name itself without arguments or even the opening or closing braces.
It means that a reference of the function is passed in the function call.
Because functions are first-class objects in JavaScript, we can treat functions like objects, so we can pass functions around like variables and return them in functions and use them in other functions. When we pass a callback function as an argument to another function, we are only passing the function definition. We are not executing the function in the parameter. We aren’t passing the function with the trailing pair of executing parenthesis () like we do when we are executing a function.
And since the containing function has the callback function in its parameter as a function definition, it can execute the callback anytime. This allows us to execute the callback functions at any point in the containing function.
It is important to note that the callback function is not executed immediately. It is “called back” (hence the name) at some specified point inside the containing function’s body.
$('body').on("click", youclick);
function youclick(e){
console.log("testing");
e.stopPropagation();
}
Upvotes: 1
Reputation: 67207
Just pass the reference
of that function
itself. And you don't need to pass the event
, you can receive that through global scope
,
Try,
$('body').on("click", youclick);
function youclick(e){
console.log("testing");
e.stopPropagation();
}
Upvotes: 3