data_type
data_type

Reputation: 27

Why is my Auto-Clicker script getting this Uncaught TypeError?

So, I'm new to JavaScript and I am trying to make an auto-clicker script. The problem is when I execute the script in the Developer Console, I get an error called "button.click is not a function" and the error just loops forever and the console. Here is my code:

var button = document.getElementsByClassName("btn btn-default");
setInterval(function(){
    button.click()  
},200)

How do I fix this?

Upvotes: 1

Views: 217

Answers (2)

dhilt
dhilt

Reputation: 20814

Due to specification, getElementsByClassName returns an array-like object of all child elements which have all of the given class names. So your "button" could not have click property, it's an array. You need to take an element, for example the first element:

var button = document.getElementsByClassName("btn btn-default")[0];

But I would say that if you have a button click handler logic and you want to run it by some timer, then the best way would be to extract that logic into a function (let's name it onClick) and run this function by timer instead of click event emulation:

var onClick = function () {
  console.log("click!");
  // your click hanlder logic
};

setInterval(onClick, 200);

button.addEventListener("click", onClick);

This also means that you don't bind the handler with onclick attr (<button onclick="onClick()">), but with addEventListener, and this is preferable way to provide events handling.

Upvotes: 1

ferhado
ferhado

Reputation: 2604

document.getElementsByClassName returns an array check this example:

<button class="btn-default" onclick="console.log('clicked');"></button>
<script>
var button = document.getElementsByClassName("btn-default")[0];
setInterval(function(){
    button.click()  
},1000)
</script>

Upvotes: 2

Related Questions