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.

jQuery code to show the working of click() method:

Code #1:
In the below code, no function is passed to this method.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:
Both outputs get generated simultaneously-

Code #2:
In the below code, function is passed to this method.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:
Before clicking inside the block-

After clicking inside the block-



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.