jQuery | click() with Examples
The click() is an inbuilt method in jQuery that starts the click event or attach a function to run when a click event occurs.
Syntax:
$(selector).click(function);
Parameter: It accepts an optional parameter “function” which is used to run when a click event occurs.
Return Value: It returns the selected element with specified function to perform.
Code #1:
In the below code, no function is passed to this method.
<html> <head> <script </script> <!-- jQuery code to show the working of this method --> <script> $(document).ready(function() { $("p").click(); }); </script> <style> p { display: block; width: 300px; padding: 20px; font-size: 30px; border: 2px solid green; } </style> </head> <body> <!-- click on this method --> <p onclick="alert('paragraph was clicked')">This is a paragraph.</p> </body> </html> |
Output:
Both outputs get generated simultaneously-


Code #2:
In the below code, function is passed to this method.
<html> <head> <script </script> <script> <!-- jQuery code to show the working of this method --> $(document).ready(function() { $("p").click(function() { $(this).fadeOut(); }); }); </script> <style> p { display: block; width: 370px; padding: 25px; font-size: 25px; border: 2px solid green; } </style> </head> <body> <!-- click on this paragraph and the paragraph will disappear --> <p>Click inside this block and whole block will disappear !!!</p> </body> </html> |
Output:
Before clicking inside the block-

After clicking inside the block-

Recommended Posts:
- How to distinguish left and right mouse click using jQuery?
- How to perform click-and-hold operation inside an element using jQuery ?
- jQuery | eq() with Examples
- jQuery | one() with Examples
- jQuery | on() with Examples
- jQuery | last() with Examples
- jQuery | after() with Examples
- jQuery | val() with Examples
- jQuery | has() with Examples
- jQuery | first() with Examples
- jQuery | removeProp() with Examples
- jQuery | replaceAll() with Examples
- jQuery | not() method with Examples
- jQuery | removeAttr() with Examples
- jQuery | replaceWith() with Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



