Search code examples
javascriptcssonclickgridz-index

exchange elements in stack with javascript


I want elements to toggle their order as I click on them. It seems z-index value is always 1. I can't figure out with this fails:

<html>
  <head>
    <title></title>
  </head>
  <style>
    .conteneur {
        display: grid;
    }
    .contenus {
        grid-column: 1;
        grid-row: 1;
        width: 100px;
        height: 100px;
    }
    
    .premier {
        background-color: red;
        z-index: 0;
    }
    
    .second {
        background-color: green;
        z-index: 1;
    }
  </style>

  <script>
    function echange() {
        let elts = document.getElementsByClassName("contenus");
        for (let i=0; i < elts.length; i++) {
            let z = elts[i].style.zIndex;
            elts[i].style.zIndex = (z + 1) % 2;
        }
    }
  </script>

  <body>
    <div class="conteneur">
      <div class="contenus premier" onclick="echange()"></div>
      <div class="contenus second" onclick="echange()"></div>
    </div>
  </body>
</html>


Solution

  • There're several issues:

    • You need to get the computed styles by window.getComputedStyle since the z-index is not an inline style.

    • the zIndex is a string, so z + 1 will end up 11, you need to parse it into number by adding + in front of it before doing the calculation

    <html>
      <head>
        <title></title>
      </head>
      <style>
        .conteneur {
            display: grid;
        }
        .contenus {
            grid-column: 1;
            grid-row: 1;
            width: 100px;
            height: 100px;
        }
        
        .premier {
            background-color: red;
            z-index: 0;
        }
        
        .second {
            background-color: green;
            z-index: 1;
        }
      </style>
    
      <script>
        function echange() {
            let elts = document.getElementsByClassName("contenus");
            for (let i=0; i < elts.length; i++) {
                let z = getComputedStyle(elts[i]).zIndex;
                elts[i].style.zIndex = (+z + 1) % 2;
            }
        }
      </script>
    
      <body>
        <div class="conteneur">
          <div class="contenus premier" onclick="echange()"></div>
          <div class="contenus second" onclick="echange()"></div>
        </div>
      </body>
    </html>