JavaScript - bring div element to front on click

0 points
Created by:

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>

      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;

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

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

      red.addEventListener('click', function() { = ++counter;

      green.addEventListener('click', function() { = ++counter;

      blue.addEventListener('click', function() { = ++counter;

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.

❤️💻 🙂