skip to Main Content

Build six squares with no color
Every time you click one, it turns green
When the last square turns green, they all go back to no color in backwards sequence to which it was clicked (not all at once)

const buttons = document.querySelectorAll(".square");

    for (const button of buttons) {
        button.addEventListener("click", UpdateSquares);
    }

    let array_sqr = [];

    function UpdateSquares(event) {
        const btn = event.target;
        btn.style.backgroundColor = 'green';
        array_sqr.push(btn.id);
    
    if (array_sqr.length == 6) {
        ReverseSquares();
    }
    }
    function ReverseSquares() {
        array_sqr.reverse();
    
    for (const [index, id] of array_sqr.entries()) {
        const reverseBtn = document.getElementById(id);

        setTimeout(() => {
        reverseBtn.style.backgroundColor = 'white';
  }, index * 1000);
  
  array_sqr = []; 

    }
}```

2

Answers


  1. You have some errors here:

    1. Add buttons to array_sqr directly. You don’t need to use id attribute for that.
    2. You clear your array_sqr inside the for loop, you should do it after the loop. Though it works because the for loop still uses an iterator from the old array value it looks bad, and there’s no need to assign a new empty array value several times while iterating.
    3. You could replace your for loop with Array::forEach() to make it more compact and clear and avoid that problem with assigning array_sqr.
    4. Use a array_sqr.length == buttons.length check to allow any number of buttons in the future.
    5. Since ReverseSquares() isn’t reused anywhere there’s no need in it – just make the code inline.
    const buttons = document.querySelectorAll(".square");
    
    for (const button of buttons) {
      button.addEventListener("click", UpdateSquares);
    }
    
    let array_sqr = [];
    
    function UpdateSquares(event) {
      const btn = event.target;
      btn.style.backgroundColor = 'green';
      array_sqr.push(btn);
    
      if (array_sqr.length == buttons.length) {
        array_sqr.reverse().forEach((btn, index) => setTimeout(() => btn.style.backgroundColor = 'white', ++index * 300))
        array_sqr = []; 
      }
    }
    .square{
      display:inline-block;
      border:1px solid gray;
      margin:5px;
      border-radius:4px;
      height:32px;
      width:32px;
    }
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
    Login or Signup to reply.
  2. const cn='green'; // colour of clicked cells.
    const spd=500;    // how fast the items are removed.
    let selection=[]; // keep track of clicked items.
    
    
    document.querySelector('.squares').addEventListener('click',e=>{
      let col=document.querySelectorAll('.squares span');
      // store reference to clicked item only if it is not already in selection array
      // which could be done either using !arr.includes or, as here, by testing the
      // item is not already green.
      if( e.target instanceof HTMLSpanElement && !e.target.classList.contains( cn ) ){
        selection.push( e.target );
        e.target.classList.add( cn )
      }
      
      // when the number of selected items reaches the total number 
      // of these items, reverse colours using a timed approach to
      // ensure that one sees the full effect.
      if( selection.length==col.length ){
        // wait 1s before removing, in reverse sequence
        setTimeout(()=>{
          selection.reverse().forEach((n,index)=>{
             setTimeout(()=>{
              n.classList.remove( cn )
             }, spd * index );
          });
          
          // reset the array so that it can be used once again.
          selection=[];  
        },1000);
      }
    });
    .squares span{ 
      cursor:pointer;
      width:2rem;
      height:2rem;
      display:inline-block;
      border:1px solid black;
      margin:0.25rem
    }
    .green{
      background:green;
    }
    <div class='squares'>
      <span></span>
      <span></span>
      <span></span>
      <span></span>
      <span></span>
      <span></span>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search