How to run a code on click event in jQuery ?
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 = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" > </ 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 >w3wiki</ h1 > < h3 > How to run a code on click event in jQuery? </ h3 > < p onclick = "alert('paragraph was clicked')" > w3wiki: A computer science portal </ p > </ body > </ html > |
Output:
Contact Us