jQuery click() Method
A jQuery click event occurs when you click on an HTML element. The jQuery click() method is used to trigger a click event. For example, clicking a paragraph on a document (web page) will trigger a $(‘p’).Click() click event. We can combine the function with the click() method to execute the function when a click event occurs, this way we can execute a piece of code whenever a click event is triggered. In this guide, we will learn about the jQuery click() method.
jQuery click() Method Syntax
$(selector).click(function(){ //A block of code that runs when a click event is triggered });
jQuery click() Method example
In the following example, when you click on a paragraph, it disappears. This is because we have associated the click() method with the paragraph selector and in the custom function we hide the current component using the hide() method. When a paragraph is clicked, a custom function is run within the click event.
<!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 thecodehubs.com. This paragraph will be hidden when you click on it.</p> </body> </html>
jQuery On click() Method
I prefer .on over .click because the former memory can use less memory and work for dynamically added elements, the simple difference between a click and onclick method in jquery.
jQuery On click() Syntax
$(selector).on('click', function(){ //A block of code that runs when a click event is triggered }); $(document).on('click', 'selector', function(){ //A block of code that runs when a click event is triggered });
where we add new buttons using jQuery
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> <script> $(document).ready(function(){ $('.add-button').click(function() { var button1 = '<button class="button1">Click</button>'; var button2 = '<button class="button2">On Click</button>'; var button3 = '<button class="button3">Document On Click</button>'; $('body').append(button1 + button2 + button3); }); // click $('.button1').click(function() { alert('Click'); }); // on click $('.button2').on('click', function() { alert('On Click'); }); // document on click $(document).on('click', '.button3', function() { alert('Document On Click'); }); }); </script> </head> <body> <button class="add-button">Add Button</button> </body> </html>
Result