TIL getting the height with Javascript
POSTED ON:
TAGS: javascript size css
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'}
Related TILs
Tagged: javascript