ulissess
ulissess

Reputation: 23

automatically clicking a button in javascript

I have this button:

<button class="btn btn-primary" type="button">Display</button>

and I'd like to click automatically that button every 100ms, I wrote this script but it doesnt work:

window.onload = function(){
  var button=document.getElementsByClassName("btn btn-primary");
  setInterval(function(){ 
    button.click();
  }, 100);
)

Upvotes: 0

Views: 1010

Answers (3)

gnorman
gnorman

Reputation: 163

Many selectors can yield multiple results, so you must specify an index to work with a selected element. If there is only one result the index will be [0].

window.onload = function(){
  var button=document.getElementsByClassName('btn btn-primary')[0];
  setInterval(function(){ 
    button.click();
  }, 100);
}

Also if this script runs before your button has loaded, the selector will not yield any results and could produce an error - here is one solution for that:

window.onload = function(){
  setInterval(function(){
    if (typeof document.getElementsByClassName('btn btn-primary')[0]!="undefined"){
        document.getElementsByClassName('btn btn-primary')[0].click();
    }
  }, 100);
}

The above script will repeatedly check whether the selected element is defined before clicking it (then continue to do so indefinitely since you don't have any mechanism to toggle it off). You also had a ")" at the last line of your sample code which I think should have been a "}".

Upvotes: 0

Văn Quyết
Văn Quyết

Reputation: 2526

getElementsByClassName return a NodeList instead of an Element. Try to use querySelector

window.addEventListener('load', function () {
  var button = document.querySelector(".btn.btn-primary");
  setInterval(function () { 
    button.click();
  }, 100);
});

If you want apply with all matched buttons, you can use querySelectorAll and [].slice.call to convert NodeList to Array

window.addEventListener('load', function () {
  var buttonList = document.querySelectorAll(".btn.btn-primary");
  var buttons = [].slice.call(buttonList);
  setInterval(function () { 
    buttons.forEach(function (button) {
        button.click();
    });
  }, 100);
});

Upvotes: 1

shubham anand
shubham anand

Reputation: 13

For making a button click automatically, it is better to pass the function in setInterval Method.

setInterval(function(){
	alert('Working fine'); //Same function as it was supposed on click
}, 5000);

To see the working model, I have attached a JS Fiddle to it. https://jsfiddle.net/xrefwqcj/2/

Upvotes: 0

Related Questions