How to click a button every second using JavaScript?
-
5but... why? maybe some context would help? ie there could be a better way to achieve what you are trying to do... rather than 'click'ing a button every second...Damien-Wright– Damien-Wright2010-12-23 04:54:14 +00:00Commented Dec 23, 2010 at 4:54
-
2Because decisionproblem.com/paperclipsDarvanen– Darvanen2019-06-15 08:10:44 +00:00Commented Jun 15, 2019 at 8:10
Add a comment
|
6 Answers
setInterval(function () {document.getElementById("myButtonId").click();}, 1000);
4 Comments
Damien-Wright
is that actually emulating a button click or just calling the event listener for
myButtonId??Kelsey Hannan
Can you do this by targeting a button by its class name instead?
John Hartsock
@Kelseydh Yes you could, but remember getElementsByClassName() will return an array of elements and not just one. Therefore you would need to iterate over the array force the click execution. also note this method is present in I all current browsers but not available in some older browsers. here is some reference. developer.mozilla.org/en-US/docs/Web/API/Document/…
John Hartsock
@Kelseydh. I also answered this for a pure JAVASCRIPT impementation. JQuery provides a slicker interface to handle this.
This will give you some control over the clicking, and looks tidy
<script>
var timeOut = 0;
function onClick(but)
{
//code
clearTimeout(timeOut);
timeOut = setTimeout(function (){onClick(but)},1000);
}
</script>
<button onclick="onClick(this)">Start clicking</button>
3 Comments
doppelgreener
Is there any reason this one clears and recreates its own timer every time it's called, as opposed to using
interval = setInterval(...) which repeats on its own, and using clearInterval(interval) when necessary?Isaac
Each time you click it, it starts another loop, just figured I would halt it inside the loop so you could do a condition check before starting it again. Also, this is using
setTimeout which is just to show an alternate method to setIntervaldoppelgreener
Alright, sure, this is a decent alternative depending on the effect someone wants. +1
document.getElementById('youridhere').click()
1 Comment
greedybuddha
This only partially answers the question, the repeating part of the question is still oustanding.
This would work
setInterval(function(){$("#myButtonId").click();}, 1000);
1 Comment
Ani Menon
Adding some description would help.
this will work ,simple and easy
<form method="POST">
<input type="submit" onclick="myFunction()" class="save" value="send" name="send" id="send" style="width:20%;">
</form>
<script language ="javascript" >
function myFunction() {
setInterval(function() {
document.getElementById("send").click();
}, 10000);
}
</script>