Observe size change of element

This is not a duplicate! I’m not satisfied with the result of other answers. If you still think it is a duplicate, please comment it before why you think it is!


I have to observe size changes of elements. I’ve tried to do it by creating a setter on the offsetWidth property like this:

const div = document.querySelector("div");

div.addEventListener("resize", console.log);
div.addEventListener("click", () => console.log(div.offsetWidth));


let width = div.offsetWidth;
Object.defineProperty(div, "offsetWidth", {
    get: () => width,
  set: val => {
    width = val;
    div.dispatchEvent(new Event("resize"));
  }
});

document.querySelector("button").onclick = () => div.style.width = "200px";
div {
  background-color: #f00;
  width: 300px;
  height: 300px;
}
<div></div>
<button>
Set size
</button>

Click on the red box to log the size. Then press the button. Nothing happens. If you click the box again, it will still show the old size. Why does this not work?

104 thoughts on “Observe size change of element”

  1. You really make it appear so easy with your presentation but I find this matter to
    be actually one thing which I think I might never understand.
    It sort of feels too complex and very large for me.
    I am having a look ahead to your next submit, I will attempt to
    get the hold of it!

    Reply
  2. Very nice post. I just stumbled upon your blog and wanted to say that I have really loved
    browsing your weblog posts. After all I will be subscribing for your feed and I
    hope you write again very soon!

    Reply