I wanted to detect value changes on the display CSS property by changes on the class attribute, and I came up with the below snippet.
I know getComputedStyle returns a read-only live CSSStyleDeclaration object, but as the object updates automatically when the element's styles are changed, I've assumed it assigns its properties somehow.
But it didn't call the getter and the setter. Why does this happen and then how does it assign its properties when it's read-only?
let parent = document.querySelector(".parent");
let child = parent.querySelector(".child");
let style = getComputedStyle(child);
let display = Symbol("display");
style[display] = style.display;
Object.defineProperty(style, "display", {
get() {
console.log("getter");
return style[display];
},
set(value) {
console.log("setter", value);
style[display] = value;
}
});
let button = document.querySelector("button");
button.addEventListener("click", () => {
child.classList.toggle("hide");
});
.child {
height: 100px;
background-color: #80a0c0;
}
.hide {
display: none;
}
<button>Toggle</button>
<div class="parent">
<div class="child"></div>
</div>