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 »
save
listen
AI Answer
How to trigger click event without clicking in Javascript
10
If you want to trigger click event without clicking a button manually, then you should us…
asked
Apu
10 answers
2915
If you want to trigger click event without clicking a button manually, then you should us…
Answer Link
answered
Apu
<button id="myButton" onclick="alert('Hello World')">Click Me</button>
<script>
const element = document.getElementById('myButton');
const event = new Event('click');
element.dispatchEvent(event);
</script>
const element = document.getElementById('myButton');
element.click();
const element = document.getElementById('myButton');
const event = new CustomEvent('click', { detail:{ key: 'value' }});
element.dispatchEvent(event);