0
<!doctype html>
<html>
<head>
<script src="jquery.js"></script>
</head>
<body>
    <script>
        function show1(){
            $("#btn").click(show2());
            window.alert("1st show");
        }

    function show2(){
        $("#btn").click(show3());
        window.alert("2nd show");
    }

        function show3(){
            window.alert("3rd show");
        }


    </script>
    <button id="btn" onclick="show1()">Show</button>

</body>
</html>

I dont understand the behavior of the code above. After setting the $("#btn").click(show2());, the function is executed even though I din't clicked the button. Why?

3 Answers 3

1

Since these are callbacks, you need to follow this

$("#btn").click(show2);

or this

$("#btn").click(function(){ show2(); });

Otherwise, if you use show2(), you will invoke the function because it will not be a reference to the function.

Sign up to request clarification or add additional context in comments.

Comments

1

You need to pass a function reference as the event handler, in your case you are invoking the handle function and is passing the value returned by it as the handler

$("#btn").click(show2);//no () at the end

Demo: Fiddle

Comments

1

Try like this

function show1(){
            $("#btn").click(show2);
            window.alert("1st show");
}
 function show2(){
        window.alert("2nd show");
}

Try to catch event by using .on

function show1(){
                $("#btn").on("click",show2);
                window.alert("1st show");
    }
     function show2(){
            window.alert("2nd show");
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.