jquery
  1. jquery-click

JQuery click()

The click() method in jQuery is used to attach an event handler function to an element that will be executed when the element is clicked.

Syntax

The syntax for using the click() method is as follows:

$(selector).click(function(){
  // function code here
});

The selector is used to target the HTML element you want to add the event handler to. The function() is the event handler function that will be executed when the element is clicked.

Use

The click() method is used to add interactivity to your web pages. You can use it to perform various actions when an element is clicked, such as changing the style of an element, displaying a message, or submitting a form.

Example

Here is an example of using the click() method to change the text of a button when it is clicked:

<!doctype html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
      $(document).ready(function(){
          $("button").click(function(){
              $(this).text("Clicked!");
          });
      });
    </script>
  </head>
  <body>
    <button>Click Me!</button>
  </body>
</html>
Try Playground

In this example, we use the click() method to target a button element. When the button is clicked, the text of the button changes to "Clicked!".

Summary

The click() method in jQuery is a powerful tool for adding interactivity to your web pages. You can use it to perform a range of actions based on user input, making your pages more dynamic and engaging. With its simple syntax and versatile functionality, click() is a must-have tool in any web developer's toolkit.

Published on: