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>
You need to use the script tag. As almost everything we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events etc. as soon as the DOM is ready. If you want an event to work on your page, you should call it inside the $(document).
The fix is easy enough, simply bind the OnClick event to the parent of the elements you want to be able to click on. That way, if the element you want to click on is removed and re-appended, the handler will still be there listening as the parent was never removed.
So onclick creates an attribute within the binded HTML tag, using a string which is linked to a function. Whereas . click binds the function itself to the property element.
$("#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); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With