Exogenist
7/21/2017 - 9:30 PM

z-index layering with javascript

null created by swainsonfitz - https://repl.it/JcsS/5

function layering() {
    var count = 0;
    var arr = [];
    var layer1, later2, layer3 = 0;
    for (var i = 1; i <= 3; i++) {
        var temp = ".layer-" + i;
        arr.push(document.querySelector(temp));
    }


    for (var m = 0; m <= 2; m++) {
        arr[m].addEventListener("click", function () {
            count += 1
            this.style.zIndex = count;
            console.log("you clicked on " + this.className);
        });
    }

}

layering();
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>positioning div's</title>
    <link href="index.css" rel="stylesheet" type="text/css" />
  </head>
  <body>

    <div class="content">
      <div class="layer-1">layer-1</div>
      <div class="layer-2">layer-2</div>
      <div class="layer-3">layer-3</div>
      <br>
    </div>
    <p>Click on the square to change its ordering and bring it to the top</p>
    
    <script src="index.js"></script>
  </body>
</html>
.layer-1 {
  height: 100px;
  width: 100px;
  
  background-color: red;
  
  position: absolute;
  top: 0;
  left: 0;
}

.layer-2 {
  height: 100px;
  width: 100px;
  
  background-color: yellow;
  
  position: absolute;
  top: 30px;
  left: 30px;
}

.layer-3 {
  height: 100px;
  width: 100px;
  
  background-color: green;
  
  position: absolute;
  top: 60px;
  left: 60px;
}

.content {
  position: relative;
  height: 160px;
  width: 160px;
}