Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a function in jQuery with click()

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> 
like image 625
Edward Tanguay Avatar asked Jan 15 '09 16:01

Edward Tanguay


People also ask

How can I call function in jQuery?

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).

Why click function is not working in jQuery?

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.

What is difference between click and Onclick in jQuery?

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.


1 Answers

$("#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); }); 
like image 52
Tiago Avatar answered Sep 18 '22 17:09

Tiago