-1

How can we use JavaScript to trigger more than one button? I have 4 buttons. When button 1 is press I want it to auto press button 2 3 and 4 but it should wait 1 second between each press.

<script>
    <button id="2" onclick="myFunction()">Click me</button> 
    <button id="3" onclick="myFunction()">Click me</button>
    <button id="4" onclick="myFunction()">Click me</button>
</script>

<body><button id="1" onclick="myFunction(buttons)">Click me</button> </body>
Jerry Seigle
  • 233
  • 4
  • 15

1 Answers1

1

You cannot wrap buttons in script tags. Perhaps you meant

const buts = [];
let cnt = 0;
const clickThem = () => {
  if (cnt >= buts.length) return;
  buts[cnt].click();
  setTimeout(clickThem,1000);
  cnt++
}
window.addEventListener("load", function() {
  document.getElementById("buttons").addEventListener("click", function(e) {
    const tgt = e.target;
    if (tgt.classList.contains("autoclicked")) { // any of the auto clicked button
      console.log("Button id", tgt.id); // or call a function
    }
  })
  document.getElementById("button1").addEventListener("click",function() {
    for (let sibling of this.parentNode.children) { // or document.querySelectorAll(".autoclicked")
      if (sibling !== this) buts.push(sibling);
    }
    clickThem();
  })
})
<div id="buttons">
  <button id="button1">Click me</button>

  <button class="autoclicked" id="button2">Click me</button>
  <button class="autoclicked" id="button3">Click me</button>
  <button class="autoclicked" id="button4">Click me</button>
</div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236