Home > Back-end >  Clicking two separate buttons with javascript
Clicking two separate buttons with javascript

Time:08-12

I'm trying to make an auto clicker with Javascipt. I'm trying to click two separate buttons in sequence. There should be 1 second between each click. When I run the following code, only one button can be clicked.

How can I fix this? Thanks in advance!

Buttons:

  <button >Button 1</button>

  <button >Button 2</button>

Code:

    var elements = document.getElementsByClassName('btn-primary');
setInterval(function(){

for (var i=0;i<elements.length; i  ) {
    elements[i].click();
}
},1000)

var elements = document.getElementsByClassName('btn-secondary');
setInterval(function(){

for (var i=0;i<elements.length; i  ) {
    elements[i].click();
}
},1000)

CodePudding user response:

That's because you use var and accidentally override the elements variable. Try never to use var.

I also changed the code to use modern syntax:

const button1 = document.querySelector('.btn-primary');
setInterval(() => {
  button1.click()
}, 1000)

const button2 = document.querySelector('.btn-secondary');
setInterval(() => {
  button2.click()
}, 1000)
<button  onclick="console.log('1')">Button 1</button>

<button  onclick="console.log('2')">Button 2</button>

CodePudding user response:

In the code snippet provided there are two problems:

  • Usage of var element twice for different values
  • The intended difference between both clicks is one second, but that code would leave the click events happen nearly simultaneously

Below is a modification of the code using setTimeout and functions.

setTimeout would call the other function after a difference of 1 second, so every click would be 1 second apart.

function clickPrimaryBt() {
  var elementsPrimary = document.getElementsByClassName('btn-primary');
  elementsPrimary[0].click();
  console.log('click1')
  setTimeout(clickSecondaryBt, 1000);
}

function clickSecondaryBt() {
  var elementsSecondary = document.getElementsByClassName('btn-secondary');
  elementsSecondary[0].click();
  console.log('click2')
  setTimeout(clickPrimaryBt, 1000);
}

clickPrimaryBt();
<button >Button 1</button>

<button >Button 2</button>

Here's a JSFiddle for the same: https://jsfiddle.net/vq8xb5oL/1/

  • Related