Skip to content

Instantly share code, notes, and snippets.

@matthewpenkala
Last active September 28, 2023 11:09
Show Gist options
  • Save matthewpenkala/3b11db76dce7f258a04184ff9745c6b7 to your computer and use it in GitHub Desktop.
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.
/**
* @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)); */
@matthewpenkala
Copy link
Author

matthewpenkala commented Sep 28, 2023

MINIFIED & COMPRESSED (calculateZIndex.min.js)

function calculateZIndex(a){let b=0,c=a;for(;c;){const e=window.getComputedStyle(c);var d=parseInt(e.getPropertyValue("z-index"),10);if(!isNaN(d)&&0!==d){b=d;break}c=c.parentElement}return b}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment