I am trying to bind a click function to an HTML element.
So i tried this :-
$("#buttonId").click(alert("hey")); // does not work.
And then i tried this :-
$("#buttonId").click(function() {
alert("hey");
}); // works perfectly fine.
Since alert is also a function, why i can’t directly pass it.
Can somebody please put some light on this ?
Click method documentation is available here http://api.jquery.com/click/
In the second example you’re passing a function to the
click()method but not calling it. When someone clicks on the element, jQuery will then call the function for you.In the first example however, you’re calling “
alert("hey")” (which returnsundefined), and that value is passed to theclickmethod.