How to trigger an event without clicking the button in javascript

Suppose, you have a button and whenever you want to load the page, the button will be called.

To trigger an event without clicking the button in javascript, you should use the click() method.

Syntex:

document.getElementById('my-btn').click();

Just two steps to click a button dynamically in Javascript on page load.

Step 1: Create a <button> element with the id attribute and set its value to my-btn.

<button id="my-btn">Click me</button>

Step 2: Call the Javascript's click() method to trigger the button event.

Example : click the button on page load.
<button onclick="alert('I am clicked')" id="my-btn">
 Don't click me
</button>
<script>
 const myBtn = document.getElementById('my-btn')
 myBtn.click()
</script>
Try it Yourself »

Click the button after 5 seconds.

If you are thinking about to click the button after 5 seconds, then you may use the setTimeout() method.

Basically, the setTimeout() method calls a function after a number of milliseconds.

Example : click the button after 5 seconds.
<button id="my-btn" onclick="alert('You clicked me')">
   Click me
</button>
<script type="text/javascript">
  setTimeout(function() {
    document.getElementById('my-btn').click();
    }, 5000)
</script>
Try it Yourself »