Home > Net >  ResizeObserver elements are always empty
ResizeObserver elements are always empty

Time:05-27

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" >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.

CodePudding user response:

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);
  }
});
  • Related