EN
JavaScript - bring div element to front on click
0
points
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:
- create three
div
elements, - create global
counter
variable to store value forz-index
property, - add event listeners that listen for
click
events the thediv
elements, - click handler functions increment the global
counter
and setz-index
property of the clickeddiv
element to the newcounter
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>
Reusable code 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>
function createStack(counter) {
if (counter == null) {
counter = 0;
};
return {
registerElement: function(element) {
var onMouseDown = function(e) {
element.style.zIndex = String(++counter);
};
element.addEventListener('mousedown', onMouseDown);
var remove = function() {
if (remove) {
element.removeEventListener('mousedown', onMouseDown);
remove = null;
}
};
return remove;
}
}
}
// Usage example:
var stack = createStack();
stack.registerElement(document.querySelector('#red'));
stack.registerElement(document.querySelector('#green'));
stack.registerElement(document.querySelector('#blue'));
</script>
</body>
</html>