Last active
March 29, 2022 15:04
-
-
Save holmberd/2510b8279dc9025f41ac74b311002984 to your computer and use it in GitHub Desktop.
Web Components height/width
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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