How to trigger click event without clicking in Javascript

If you want to trigger click event without clicking a button manually, then you should use the click() method in Javascript.

Example : click button on page load dynamically.
<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 »

For that we will create a button with an id my-btn. So that, we can select the button using the getElementById() method.

<button id="my-btn">Don't click me</button>

We will also assign the alert() method to the onclick attribute. So that, same text can be alert whenever the button will be clicked.

<button onclick="alert('I am clicked')" id="my-btn">
   Don't click me
</button>

Now inside the <script> tag , select the created button element using the getElementById() method and store in a variable.

<script>
 const myBtn = document.getElementById('my-btn');
</script>

Finally, add the click() method.

Example
<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 »