'How to run a custom element's constructor after it has all of its required attributes?
I'm trying to create a custom element "color-box" that will need an attribute named "color" to identify the box's color.
So for example, <color-box color="green"></color-box> will give a 100 pixels wide and 100 pixels tall square, with the background-color green.
I don't have any problems when defining the element directly with HTML by doing <color-box color="red"></color-box>, everything goes fine, but in my case, I need to create this element with only javascript, like this:
let colorBoxElement = document.createElement("color-box");
colorBoxElement.setAttribute("color", "red");
document.body.appendChild(colorBoxElement)
What happens is that the constructor is getting ran before colorBoxElement.setAttribute("color", "red") and that's not what I want, because I'm using that attribute in my constructor. I want the constructor to run when all of it's required attributes are there (in this case, only 1: color) or when it's actually appended to the document body using document.body.appendChild(colorBoxElement)
Is there any possible way of doing this, or at least doing something similar to what I need? Here's my code:
// Defining the custom element
class ColorBox extends HTMLElement {
constructor() {
super()
let shadow = this.attachShadow({mode: "open"})
let container = document.createElement("div")
container.style.width = "100px"
container.style.height = "100px"
switch(this.getAttribute("color")) {
case "red":
container.style.backgroundColor = "red"
break;
case "green":
container.style.backgroundColor = "green"
break;
default:
throw new Error("Color attribute not valid: " + this.getAttribute("color"))
}
shadow.appendChild(container)
}
}
customElements.define("color-box", ColorBox)
// Creating the custom element
let colorBoxElement = document.createElement("color-box")
// This will get executed after the constructor was ran (problem)
colorBoxElement.setAttribute("color", "green")
// Appending the element to body
document.body.appendChild(colorBoxElement)
<body>
<color-box color="red"></color-box>
</body>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
