Search code examples
javascripthtmldomshow-hide

Javascript Show/Hide certain elements by clicking a button


I have 12 tiles (100px by 100px squares) on my screen.

Each tile by default is set to display:block and has a white background background: rgb(255,255,255);

If a tile is clicked, the background becomes orange rgb(255,161,53). Using the following function:

function changeColour(id){
{
    var current_bg = document.getElementById(id).style.backgroundColor;

    if(current_bg != "rgb(255, 161, 53)"){
        document.getElementById(id).style.backgroundColor = "rgb(255,161,53)";
    } else if(current_bg == "rgb(255, 161, 53)"){
        document.getElementById(id).style.backgroundColor = "rgb(255,255,255)";
    }
}

At the bottom of the page I have a button called "showHide", once it is pressed I want only the tiles with an orange background to be shown. Once it pressed again I want ALL of the tiles to appear.


Solution

  • What I meant with meta data

    A break down:

    1. The first block iterates over every tile and sets an onclick handler
    2. When you click a block it will either set orange to the class list or remove it using toggle. The actual orange coloring comes from the stylesheet. Where tiles that don't have orange in their class names :not() get a white background.
    3. When you click the show hide button you'll see the same trick. Every class list that doesn't contain orange get hidden by the hide class name that gets toggled.

    I've used a different approach here, using class names as selectors and play with them to get the desired result.

    function changeColour() {
      this.classList.toggle("orange");
    
      //if hiding is on we need to also hide that block
      if (this.parentElement.querySelectorAll("div.tiles.hide").length > 0)
      {
        this.classList.add("hide");
      }
    }
    
    var divs = document.querySelectorAll("div.tiles");
    
    //use Array.prototype.forEach to iterate over nodelist
    Array.prototype.forEach.call(divs, function(element){
      element.addEventListener("click", changeColour);
    });
    
    document.querySelector("button.hide").addEventListener("click", showHide);
    
    function showHide(){
      
      Array.prototype.forEach.call(divs, function(element){
        
        if (!element.classList.contains("orange"))
        {
          element.classList.toggle("hide");
        }
      });  
    }
    div.tiles {
      display: inline-block;
      width: 100px;
      height: 100px;
      border: 1px solid grey;
    }
    
    div.tiles:not(.orange) {
      background-color: #ffffff;
    }
    
    div.tiles.orange {
      background-color: rgb(255,161,53);
    }
    
    div.tiles.hide {
      display: none;
    }
    <div class="tiles"></div>
    <div class="tiles"></div>
    <div class="tiles"></div>
    <div class="tiles"></div>
    <div class="tiles"></div>
    
    <button class="hide">show/hide white tiles</button>