Difference between `.click(handler())` and `.click(handler)`

javascript, jquery

Solution

$("#myID").click(myFun());

This calls `myFun()` and tries to install whatever it returns as an event handler. Since it is not returning anything, you are actually triggering the click on `#myID`.

Problem

I have the following code. ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script type="text/javascript" src="jquery-1.4.2.min.js" ></script> <script type="text/javascript"> function myFun() { alert(5) } $(document).ready(function(){ $("#myID").click(myFun()); }) </script> </head> <body> <input type="button" value="Click it" id="myID" /> </body> </html> ``` When I run this code then `alert(5)` is coming when the page loads. If I write ``` $("#myID").click(myFun) ``` then the alert only appears when we click on the button. Why does it behave like this?

Original source