Open In App

How to run a code on click event in jQuery ?

Last Updated : 06 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how to run the code after clicking on an event. To run the code after clicking an event, we use the click() method. The click() method is used to run the code when a click event occurs. 

The click() method to attach a click event handler to selected elements. Inside the handler function, you can define the code to be executed when the click event occurs, such as manipulating the DOM, making AJAX requests, or performing other operations.

Syntax:

$(selector).click(function);

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

Example: In This example, we are using the above-explained method.

HTML




<!DOCTYpe html>
<html>
<head>
    <title>
        How to run a code on
        click event in jQuery?
    </title>
    <script src=
    </script>
 
    <!-- jQuery code to show the working
        of this method -->
    <script>
        $(document).ready(function () {
               $("body").css("text-align", "center");
               $("h1").css("color", "green");
               $("p").click(function () {
               $(this).css("font-size", "20px");
               $(this).css("color", "green");
            });
        });
    </script>
</head>
 
<body>
    <h1>GeeksforGeeks</h1>
 
    <h3>
        How to run a code on click event in jQuery?
    </h3>
 
    <p onclick="alert('paragraph was clicked')">
        GeeksforGeeks: A computer science portal
    </p>
</body>
</html>


Output:

click event 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads