Today I Learned - Rocky Kev

TIL getting the height with Javascript

POSTED ON:

TAGS:

Say you wanted the height of a element. How do you get that in JavaScript?

I learned about getComputedStyle, which gets you the number.

According to the MDN, there's some serious quirks:

Returned values are sometimes deliberately inaccurate. To avoid the "CSS History Leak" security issue, browsers may lie about the computed styles for a visited link, returning values as if the user never visited the linked URL. See Plugging the CSS History Leak and Privacy-related changes coming to CSS :visited for examples of how this is implemented.

During CSS transitions, getComputedStyle returns the original property value in Firefox, but the final property value in WebKit.

Via the MDN: https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle

A major one is that browsers may cache computed styles for a given element, which can result in unexpected behavior if styles are changed dynamically. To avoid this issue, you may need to force the browser to recalculate styles by triggering a reflow.

Instead, it's better to use computedStyleMap instead!

Via the MDN: https://developer.mozilla.org/en-US/docs/Web/API/Element/computedStyleMap

Here's the code:

const elementWidth = getComputedStyle(myElement).width;
// returns '300px'


const elementWidth = myElement.computedStyleMap().get('width');
// returns CSSUnitValue {value: 300, type: 'px'}

via The Typed Object Model


Related TILs

Tagged:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.