ResizeObserver elements are always empty

463 views Asked by At

I want to be able to use ResizeObserver on multiple elements on my page, and each will trigger the same function call (on the resized element). But sadly instead of DOM objects, the function just seems to receive empty objects.

Given one or more...

<div id="test" class="rg_toggle">Test</div>

... this code ...

    function fixToggle( toggleElement) {
      alert(JSON.stringify(toggleElement, ["id", "className"));
    }

    const resizeObserver = new ResizeObserver(entries => {
      for (let entry of entries) {
        fixToggle(entry)
      }
    });

    const toggles = document.querySelectorAll('.rg_toggle');
    toggles.forEach(toggle => {
      resizeObserver.observe(toggle);
    });

only ever shows {} in the alert dialog, when I was expecting the id and classname. Here's my CodePen.

1

There are 1 answers

1
ryan.c On BEST ANSWER

You can access the element which is being observed via entry.target:

const resizeObserver = new ResizeObserver((entries) => {
  for (let entry of entries) {
    fixToggle(entry.target);
  }
});