Reputation: 451
I'm trying to auto click a button after 5 seconds, it does nothing. Manually clicking works
<button id="test1" onclick="tFunction()">Button</button>
<script>
function tFunction(){
alert("Hello!");
}
setTimeout(document.getElementByID('test1').click(),5000);
</script>
Upvotes: 0
Views: 58
Reputation: 371233
setTimeout
accepts a function. What you're doing is you're immediately calling .click()
, then passing its return value to setTimeout
.
Wrap the .click()
inside a function instead:
function tFunction() {
console.log("Hello!");
}
setTimeout(() => document.getElementById('test1').click(), 5000);
<button id="test1" onclick="tFunction()">Button</button>
Also note that getElementById
is case-sensitive - the last d
should not be capitalized.
Also, don't use inline handlers, they have too many problems and have no place in modern codebases. Use addEventListener
instead:
const test1 = document.getElementById('test1');
function tFunction() {
console.log("Hello!");
}
test1.addEventListener('click', tFunction);
setTimeout(() => test1.click(), 5000);
<button id="test1">Button</button>
Upvotes: 4