Languages
[Edit]
EN

JavaScript - bring div element to front on click

0 points
Created by:
Saim-Mccullough
388

In this article, we would like to show you how to bring div element to the front on click event using JavaScript.

In the below example, we:

  1. create three div elements,
  2. create global counter variable to store value for z-index property,
  3. add event listeners that listen for click events the the div elements,
  4. click handler functions increment the global counter and set z-index property of the clicked div element to the new counter value so it moves to the front.

Runnable example:

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
  <head>
    <style>

      body {
        height: 200px;
      }

      div {
        position: absolute;
        height: 100px;
        width: 100px;
        border: 3px solid gray;
      }

      #red {
        background: #ff6666;
        border: 3px solid #ff3333;
        top: 90px;
        left: 40px;
      }

      #green {
        background: #00cc00;
        border: 3px solid #009e00;
        top: 40px;
        left: 70px;
      }

      #blue {
        background: #8080ff;
        border: 3px solid #5757ff;
        top: 60px;
      }

    </style>
  </head>
  <body>
    <p>Click on the div to bring it to the top </p>
    <div id="red"></div>
    <div id="green"></div>
    <div id="blue"></div>

    <script>
      var counter = 1;
      
      var red = document.querySelector('#red');
      var green = document.querySelector('#green');
      var blue = document.querySelector('#blue');

      red.addEventListener('click', function() {
        this.style.zIndex = ++counter;
      });

      green.addEventListener('click', function() {
        this.style.zIndex = ++counter;
      });

      blue.addEventListener('click', function() {
        this.style.zIndex = ++counter;
      });

    </script>
  </body>
</html>
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join