Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 936
Searcher Avatar asked Jun 08 '12 11:06

Searcher


3 Answers

$("#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.

like image 92
lanzz Avatar answered Oct 10 '22 21:10

lanzz


Read this .click() - Bind an event handler to the click JavaScript event, or trigger that event on an element using JavaScript.

You just need to write $("#myID").click(myFun); instead of $("#myID").click(myFun()); because when you write myFun() in your code the function is invoked immediately (rather than when a click event fires on #myID).

Working Demo

like image 34
Pranay Rana Avatar answered Oct 10 '22 21:10

Pranay Rana


Try this for running the function on the click event:

function myFun(){
    alert(5);
}

$(document).ready(function(){
    $("#myID").click(function(){
        myFun();
    });
})
like image 2
Bloafer Avatar answered Oct 10 '22 23:10

Bloafer