Open In App

jQuery click() Method

Improve
Improve
Like Article
Like
Save
Share
Report

jQuery click() is an inbuilt method that starts the click event or attaches a function to run when a click event occurs. 

Syntax:

$(selector).click(function);

Parameters:

It accepts an optional parameter “function” which is used to run when a click event occurs. 

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

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

HTML




<!DOCTYPE html>
<html>
 
<head>
    <script src=
    </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: 

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

HTML




<!DOCTYPE html>
<html>
 
<head>
    <script src=
    </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: 



Last Updated : 11 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads