Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate click with setTimeout in Javascript

How would I simulate a click event with setTimeout? Something like:

<script>
    window.onload=setTimeout(document.getElementById('mk1').click(),1000);
</script>

<a id="mk1" href="some url">click me</a>
like image 941
cj333 Avatar asked May 17 '11 13:05

cj333


2 Answers

Currently your code calls click() immediately and passes the return value to setTimeout. You instead want to pass a function reference to setTimeout:

window.onload = function() {
  setTimeout(function() {
    document.getElementById('mk1').click();
  }, 1000);
};

Edit: As @ThiefMaster points out, you also want to pass a function to onload; even though it might seem to work otherwise, it wouldn't do what it really should be doing.

like image 61
casablanca Avatar answered Oct 23 '22 00:10

casablanca


document.getElementById('mk1').click() is evaluating when the script first runs. You need to make it into a function and pass that as the first parameter.

like image 23
Briguy37 Avatar answered Oct 22 '22 22:10

Briguy37