jQuery click event occurs when you click on an html element. jQuery click() method is used to trigger the click event. For example $(“p”).click() will trigger the click event when a paragraph is clicked on a document (a web page). We can attach a function to the click() method to run the function when a click event occurs, this way we can run a piece of code every time the click event is triggered. In this guide, we will learn about jQuery click() method.
jQuery click() Method Syntax
$(selector).click(function(){ //block of code that runs when the click event triggers });
jQuery click() event example
In the following example, when you click on the paragraph, it gets hidden. This happens because we have associated the click() method to the paragraph selector and in the custom function we are hiding the current element using hide() method. The custom function inside click event runs when a click on a paragraph happens.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <script> $(document).ready(function(){ $("p").click(function(){ $(this).hide(); }); }); </script> </head> <body> <h2>jQuery click event example</h2> <p>This example is published on beginnersbook.com. This paragraph will be hidden when you click on it.</p> </body> </html>
Output:
Before clicking on the paragraph:
After clicking on the paragraph:
Another example of jQuery click event
In the following example, we have associated the click method to the id selector, we have provided the button id, so when we click on the button, the click event is triggered. In the click event function we are hiding the h2 elements using hide() method.
You can see in the output screenshots that when you click on the “Hide Heading” button, the heading of the document gets hidden.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <script> $(document).ready(function(){ $("#myid").click(function(){ $("h2").hide(); }); }); </script> </head> <body> <h2>jQuery click event example</h2> <p>This example is published on beginnersbook.com. The main heading will be hidden when you click on the "Hide Heading" button</p> <button id="myid">Hide Heading</button> </body> </html>
Output:
Before clicking the button:
After clicking the button:
Leave a Reply