Last active
September 28, 2023 11:09
-
-
Save matthewpenkala/3b11db76dce7f258a04184ff9745c6b7 to your computer and use it in GitHub Desktop.
This calculates the z-index of a given HTML element by traversing its parents and checking the computed z-index values. The function ensures an accurate determination of the z-index even if the z-index value is specified using different units or if it's inherited from parent elements.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @author Matthew Penkala <hello@matthewpenkala.com> | |
* @website https://matthewpenkala.com/ | |
* @version 1.0.0 | |
* @description This JavaScript file contains a function named `calculateZIndex` | |
* which, quite evidently, calculates the z-index (CSS) of a given | |
* HTML element by traversing its parents and checking the computed | |
* z-index values. The function ensures an accurate determination of | |
* the z-index even if the z-index value is specified using different | |
* units or if it's inherited from parent elements.*/ | |
function calculateZIndex(element) { | |
// Initialize zIndex to 0 | |
let zIndex = 0; | |
// Iterate through the element and its parents | |
while (element) { | |
// Get the computed style for the current element | |
const computedStyle = window.getComputedStyle(element); | |
// Parse the zIndexValue as an integer (base 10) | |
const zIndexValue = parseInt(computedStyle.zIndex, 10); | |
// Check if zIndexValue is valid (not NaN and not 0) | |
if (zIndexValue && zIndexValue !== 0) { | |
// Update zIndex and exit the loop if a valid zIndexValue is found | |
zIndex = zIndexValue; | |
break; | |
} | |
// Move to the parent element for the next iteration | |
element = element.parentElement; | |
} | |
// Return the calculated zIndex | |
return zIndex; | |
} | |
// Calling the function (example): | |
/* calculateZIndex(document.querySelector(element)); */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
MINIFIED & COMPRESSED (calculateZIndex.min.js)