Open In App

How to simulate a click with JavaScript ?

In this article, we are going to learn how can we simulate a click with JavaScript. To simulate a click with JavaScript we have to create a function or event.

These are the following ways to solve this problem:



Method 1: Using the click() method

Syntax:

element.click()

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






<!DOCTYPE html>
<html lang="en">
 
<head>
    <title>
          How to simulate a click with JavaScript ?
      </title>
</head>
 
<body>
    <h1 style="color: green">
        GeeksforGeeks
    </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 ?

Method 2: Creating a new CustomEvent

Syntax:

click_event = new CustomEvent('click');
btn_element = document.querySelector('#element');
btn_element.dispatchEvent(click_event);

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




<!DOCTYPE html>
<html lang="en">
<head>
    <title>
          How to simulate a click with JavaScript ?
      </title>
</head>
 
<body>
    <h1 style="color: green">
        GeeksforGeeks
    </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() {
            click_event = new CustomEvent('click');
            btn_element = document.querySelector('#btn1');
            btn_element.dispatchEvent(click_event);
        }
 
        // Simulate a click every second
        setInterval(clickButton, 1000);
    </script>
</body>
</html>

Output:

How to simulate a click with JavaScript ?


Article Tags :