Skip to content

Instantly share code, notes, and snippets.

@holmberd
Last active March 29, 2022 15:04
Show Gist options
  • Save holmberd/2510b8279dc9025f41ac74b311002984 to your computer and use it in GitHub Desktop.
Save holmberd/2510b8279dc9025f41ac74b311002984 to your computer and use it in GitHub Desktop.
Web Components height/width
static get observedAttributes() {
return ['height', 'width'];
}
get height() {
return this.hasAttribute('height') && Number(this.getAttribute('height').replace('px', ''));
}
set height(val) {
if (val) {
this.setAttribute('height', val);
} else {
this.removeAttribute('height');
}
}
get width() {
return this.hasAttribute && this.getAttribute('width');
}
set width(val) {
if (val) {
this.setAttribute('width', val)
} else {
this.removeAttribute('width');
}
}
attributeChangedCallback(name, oldValue, newValue) {
if (name === 'height') {
if (newValue !== oldValue) {
this.shadowRoot.adoptedStyleSheets[0].cssRules[0].style.height =
newValue.includes('px') ? newValue : `${newValue}px`;
}
}
if (name === 'width') {
if (newValue !== oldValue) {
this.shadowRoot.adoptedStyleSheets[0].cssRules[0].style.width =
newValue.includes('px') ? newValue : `${newValue}px`;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment