Toggle between functions

mick324

Newbie
Joined
May 19, 2021
Messages
1
Reaction score
0
JavaScript:
var btn = document.getElementsByTagName("button");

var click = 0;

function toggleFunction(click) {
  
    if(click % 2 === 0) {
      
      playerA();
      
    }
    else {
      playerB();
      
    }
  
}

toggleFunction(click);

 function playerA() {
    for(let i = 0; i <btn.length; i++) {
        btn[i].addEventListener("click", () => {
            // do something
            click++;
        });
    }
   return click;
 }
I have a problem with toggling between two almost identical functions playerA and playerB. I tried so many things like removing Event Listener and making flags, but it didn't work. I appreciate any help.
 
Do you have multiple buttons? I feel like you do. In this case you have to set a variable for each button. One single "var click=0;" is not suffice. Button 2 will change the state of button 1.

I recommend setting a "data-clicked" for each button using this: https://plainjs.com/javascript/attributes/setting-getting-and-removing-data-attributes-8/

For example a button is 'data-clicked=0' at first and you set it to 1 after the click. You also use this variable to determine which function to call when the user clicks your button.
Code:
btn.addEventListener("click", () => {
    // do something
    var clicked = this.getAttribute('data-clicked');
    if (clicked == 0)
        playerA();
    else
        playerB();
    this.setAttribute('data-clicked', !clicked);
});

Something around this. You have to test it. I wrote it without debugging. But you get the idea.
 
Back
Top