jQuery click() function example

This post shows how to use the jQuery click() function with examples.

Description

Bind an event handler to the "click" JavaScript event, or trigger that event on an element.
When you click on an element, the click event occurs and once the click event occurs it execute the click () method or attaches a function to run.

Syntax

$(selector).click()  
It is used to trigger the click event for the selected elements.
$(selector).click(function)  
It is used to attach the function to the click event.

Examples

Example 1

In the below example, hide paragraphs on a page when they are clicked:
<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>click demo</title>
    <style>
        p {
            color: red;
            margin: 5px;
            cursor: pointer;
        }

        p:hover {
            background: yellow;
        }
    </style>
    <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>

<body>

    <p>First Paragraph</p>
    <p>Second Paragraph</p>
    <p>Yet one more Paragraph</p>

    <script>
        $("p").click(function() {
            $(this).slideUp();
        });
    </script>

</body>
</html>
Output:
First Paragraph

Second Paragraph

Yet one more Paragraph
Try it Yourself - Copy paste code in Online HTML Editor to see the result

Example 2

<!DOCTYPE html>
<html>

<head>
    <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
    <script>
        $(document).ready(function() {
            $("h1,h2,h3").click(function() {
                $(this).hide();
            });
        });
    </script>
</head>

<body>
    <h1>Hide h1 header</h1>
    <h2>Hide h2 header</h2>
    <h3>Hide h3 header</h3>
</body>

</html>
Output:
Hide h1 header
Hide h2 header
Hide h3 header
Try it Yourself - Copy paste code in Online HTML Editor to see the result

References

Comments