How can I dynamically adjust the position of a specific div element with the id "test" on my webpage based on its z-index using CSS's calc() and attr() functions? I want the position to change proportionally when the z-index changes.
It appears that the attr(zIndex) value is always evaluated as one, causing the element to remain in place regardless of the zIndex modifications. Is there a way to correctly access CSS values within the style definition itself, or should I handle this task entirely in JavaScript?
<!DOCTYPE html>
<html>
<head>
<title>zLinkTestPage</title>
<style>
body { background-color: #000000; }
div { margin: 0px; padding: 0px; border-width: 0px; display: block; }
#test {
position: absolute;
top: 0px;
left: calc( attr(zIndex) * 10px );/*This line is the one in question*/
background-color: #ff0000;
z-index: 0;
width: 144px; height: 288px;
}
#ref {
position: absolute;
top: 0px;
left: 0px;
background-color: #00ff00;
z-index: 1;
width: 288px; height: 144px;
}
</style>
</head>
<body>
<div id="ref">Reference div</div>
<div id="test" onmouseenter="moveZ(2);" onmouseleave="moveZ(-2);"><br /><br /><br /><br /><br /><br /><br /><br />Test div</div>
</body>
<script type="text/javascript">
function moveZ(amount) {
var box = document.getElementById("test");
var curZ = box.style.zIndex;
if(curZ == "") {
//console.log((typeof curZ) + " curZ=" + curZ);
curZ = 0; //because, for some reason, the initial value of any CSS property when accessed by JavaScript always seems to be null of some sort...
//console.log((typeof curZ) + " curZ=" + curZ);
}
else {
//console.log((typeof curZ) + " curZ=" + curZ);
curZ = parseInt(curZ);
//console.log((typeof curZ) + " curZ=" + curZ);
}
var newZ = curZ + amount;
box.style.zIndex = newZ;
}
</script>
</html>
This challenge is part of my learning process, aimed at creating more advanced projects in the future.