From what i understand, in jquery, when a method requires a function as an argument you can't just invoke a predefined function like this:
$('#target').click(myFunction());
...because "myFunction()" will be parsed and replaced with the value returned by the function...which is no longer a function.You have to put the entire function definition, in an anonymous function:
$('#target').click(function() {
alert('Handler for .click() called.');
});
...so, is there any way of just invoking the function where it's required as an argument?
You understand correctly. It is true not only in jQuery, this is how JavaScript works. When a function is needed as an argument, then you have to give a function as an argument, and not the result of its invocation. You can use this:
$('#target').click(myFunction);
but for alert you need an anonymous function because you are passing an argument.
You are passing the result of the function, not the function itself. Instead of:
click(myFunction());
use
click(myFunction);
Live example on jsfiddle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With