Home > Net >  Fluctuating between two events
Fluctuating between two events

Time:11-08

  <div >
    <button id="1">first</button>
    <button id="2">Second</button>
    <button id="3">Third</button>
    <button id="4">4th</button>
    <button id="...">...</button>
    <button id="n">nth</button>
  </div>

  <script>
    var btn = document.querySelectorAll('button')

    for (let i = 0; i < btn.length; i  ) {
      btn[i].style.border = '3px solid yellow'

      if (btn[i].style.border == '3px solid yellow') {
        btn[i].addEventListener('click', red)      
      }   
      else if (btn[i].style.border == '3px solid red') {
        btn[i].addEventListener('click', yellow)      
      }
      
    }
    function red(e) {
      this.style.border = '3px solid red'
    }
    function yellow(e) {
      this.style.border = '3px solid yellow'
    }
  </script>

It's supposed when the user toggles a button from the list it turns red and when re-toggles the same button it turns yellow and so on..

I know what happened here and why it doesn't work & I have a solution based on a counter (even or odd), but I don't reckon this method is optimal.

So what is the best way to solve the problem!

CodePudding user response:

You can store whether a button is on/off as a custom property on the DOM element:

var btn = document.querySelectorAll('button')

for(let i = 0; i < btn.length; i  ) {
    btn[i].addEventListener("click", toggleState);
}

// You could also replace the above loop with:
// btn.forEach(i => i.addEventListener("click", toggleState));

function toggleState(e)
{
    e.preventDefault();
    if(this.toggled)
    {
        this.style.border = "3px solid red";
        // Do whatever else you need to do when the border turns red
    }
    else
    {
        this.style.border = "3px solid yellow";
        // Do whatever else you need to do when the border turns yellow
    }
    this.toggled = !this.toggled;

    return;
}
  • Related