How to use the click() method In Javascript

The click() method simulates a mouse click on an element. It fires the click event of the element on which it is called, allowing the event to bubble up the document tree and trigger click events on parent elements.

Steps:

  1. Select the element to be clicked.
  2. Use the click() method to simulate the click.

Syntax:

element.click()

Example: This example shows the implementation of the above-explained approach.

html
<!DOCTYPE html>
<html lang="en">

<head>
    <title>
          How to simulate a click with JavaScript ?
      </title>
</head>

<body>
    <h1 style="color: green">
        w3wiki
    </h1>

    <b>
        How to simulate a click
        with JavaScript ?
    </b>

    <p>
        The button was clicked
        <span class="total-clicks"></span>
        times
    </p>

    <button id="btn1" onclick="addClick()">
        Click Me!
    </button>

    <script type="text/javascript">
        let clicks = 0;

        function addClick() {
            clicks = clicks + 1;
            document.querySelector('.total-clicks').textContent
                = clicks;
        }

        // Simulate click function
        function clickButton() {
            document.querySelector('#btn1').click();
        }

        // Simulate a click every second
        setInterval(clickButton, 1000);
    </script>
</body>

</html>

Output:

How to simulate a click with JavaScript ?

How to simulate a click with JavaScript ?

We will learn how to simulate a click with JavaScript. To do this, we can use either the click() method or create a new CustomEvent. Let’s explore these methods:

Table of Content

  • Method 1: Using the click() method
  • Method 2: Creating a new CustomEvent

Similar Reads

Method 1: Using the click() method

The click() method simulates a mouse click on an element. It fires the click event of the element on which it is called, allowing the event to bubble up the document tree and trigger click events on parent elements....

Method 2: Creating a new CustomEvent

The CustomEvent constructor allows you to create a new event that can be used on any element and handle specific events. By passing the ‘click’ event to the constructor, you can create a custom click event....