skip to Main Content

I`m trying to disabled 6 buttons when a condition is met. I have given the buttons the same class. Is there a simplest/shorter way to write ;

var ButtonCollection = document.getElementsByClassName("button");
function PopUp() {
      x = L + Y;
      
      var Count = 0;
      MonsterDiv2.addEventListener("click", function () {
        Count += 1;
        if (Count == 2) MonsterDiv2.style.display = "none";
        ActionList.innerHTML += `<li>.</li>`;
        ButtonCollection[0].disabled = false;
        ButtonCollection[1].disabled = false;
        ButtonCollection[2].disabled = false;
        ButtonCollection[3].disabled = false;
        ButtonCollection[4].disabled = false;
        ButtonCollection[5].disabled = false;
        //
      });
    }

2

Answers


  1. Hopefully, this is what you are looking for. Also maybe I would suggest replacing the enableButtons() function with toggleButtons(), it will be more universal.
    And don’t forget to clean the EventListener 🙂

    const buttonsCollection = document.getElementsByClassName("button");
    const enableButtons = () => {
      buttonsCollection.forEach((button) => {
        button.disabled = false
      })
    }
    const popUp = () => {
      x = L + Y;
      
      let count = 0;
      monsterDiv2.addEventListener("click", () => {
        count += 1;
    
        if (count === 2) monsterDiv2.style.display = "none";
    
        enableButtons()
      });
    }
    
    Login or Signup to reply.
  2. I guess the first thing you could do is refactoring the ButtonCollection[<index>].disabled = false;

    You could do so by writing the following code:

    Array.from(ButtonCollection).forEach(el => {el.disabled = false})
    

    Note that you have to convert HTMLCollection to array before using the forEach method

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search