I am trying to build a responsive custom element in vanilla JS that can respond to changes to its computed dimensions. I have successfully been able to observe changes to explicitly defined properties/attributes. However, I am wondering if it is possible to observe changes to the computed properties of the custom element. For example:
class Custom_element extends HTMLElement {
generate_html() {
return `
<style>
:host {
display:block;
}
#element_wrapper {
border: 1px solid grey;
max-height : 100%;
max-width : 100%;
min-height : 100%;
min-width : 100%;
}
</style>
<div id="element_wrapper">
<slot></slot>
</div>
`
};
constructor() {
super();
this.root = this.attachShadow({
'mode': 'open'
});
this.root.innerHTML = this.generate_html();
}
static get observedAttributes() {
return ['height', 'width'];
}
attributeChangedCallback(name, oldVal, newVal) {
console.log(name, oldVal, newVal) //Is it possible to fire this when the css computed height/width properties change?
}
}
window.customElements.define('custom-element', Custom_element);
#container {
width: 100px;
height: 100px;
}
#container:hover {
width: 200px;
height: 200px;
}
<div id='container'>
<custom-element>
Slot Content
</custom-element>
</div>
Is it possible to get the attributeChangedCallback() to fire when you hover over the #container element and change the computed height/width of the custom element?
As @Bergi pointed out in the comments, ResizeObserver is exactly what I was looking for. Apparently there is a polyfill to help support some of the older browsers.