Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get elements heights using JS and pass into CSS variable

I want to get the height of an element and pass it into a css variable. The issue im having is when i try to pass that number into the navHeight variable it ends up returning as undefined.

<script>
    let navHeightTest = document.getElementById("navbar").offsetHeight;
    console.log(navHeightTest); // Returns the nav height as a number
    
    let navHeight = Document.documentElement.style.setProperty('--nav-height', navHeightTest);
    console.log(`Nav Height=${navHeight}`); // Returns undefined 
</script>

CSS

    :root {
        --nav-height: 101px; /* Default Fallback Value */
    }
    .dynamic-margin {
        margin-top: calc(var(--nav-height) + 2.5rem) !important;
    }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Good question – this can get confusing because setProperty returns undefined, not the value you just set.

Check out the Return value entry in the docs: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/setProperty#return_value

If you observe that the --nav-height variable isn’t being updated either it might be because you’re missing the units when you call setProperty. Since your default in the CSS is in pixels, and offsetHeight reports the number in pixels, I’m guessing you want pixels. Note the ‘px’ at the very end of the line.

let navHeight = Document.documentElement.style.setProperty('--nav-height', navHeightTest + 'px');
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading