60

In the code below, why does the open function work but the close function does not?

$("#closeLink").click("closeIt");

How do you just call a function in click() instead of defining it in the click() method?

<script type="text/javascript">
    $(document).ready(function() {
        $("#openLink").click(function() {
            $("#message").slideDown("fast");
        });
       $("#closeLink").click("closeIt");
    });

    function closeIt() {
        $("#message").slideUp("slow");
    }
</script>

My HTML:

Click these links to <span id="openLink">open</span> 
and <span id="closeLink">close</span> this message.</div>

<div id="message" style="display: none">This is a test message.</div>

1 Answer 1

139
$("#closeLink").click(closeIt);

Let's say you want to call your function passing some args to it i.e., closeIt(1, false). Then, you should build an anonymous function and call closeIt from it.

$("#closeLink").click(function() {
    closeIt(1, false);
});
Sign up to request clarification or add additional context in comments.

6 Comments

Quotes are removed from the closeIt function (it took me too long to grok that, so adding a comment to help someone else out).
@Tiago why no ()? what if you want to pass arguments?
@Damon: because that way the function will be called and the return of it will be passed to the click function. If you want to pass args, you have to do something like this: $("#closeLink").click(function(){closeIt(some, args, you, 'want');});
Why not writing a more elaborate answer ? Your last comment should be inside the answer itself ;)
@Dusty: it won't work as expected. Your code will execute the function closeit immediately with 1 and false as parameters, then the result of that call will be passed as a parameter to click. What you want it to call the function closeit only when the users clicks the thing.
|

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.