Skip to content

JavaScript ResizeObserver | Interface

  • by

Using JavaScript ResizeObserver you can notified when HTML element size changes. It provides a mechanism to monitor the changes to the dimensions of an element.

let resizeObserver = new ResizeObserver((entries) => {
  for (entry of entries) {
      // access the entry properties
  }
});

It reports changes in the dimensions of an Element’s content or border-box, or the bounding box of an SVGElement

JavaScript ResizeObserver

Simple example code observing the required element for changes.

<!DOCTYPE html>
<html>
<head>
  <style>
    #container {
      resize: both;
      border: solid gray;
      background-color: lightblue;
      height: 100px;
      width: 300px;
      overflow: auto;
    }
  </style>
</head>

<body>
  <div id="container"></div>
  <script>
    boxElem = document.querySelector('#container')

    let resizeObserver = new ResizeObserver((entries) => {
      for (entry of entries) {

        console.log('Height: ', entry.contentRect.height);
        console.log('Width:', entry.contentRect.width);
      }
    });

    resizeObserver.observe(boxElem);
  </script>

</body>
</html>

Output:

JavaScript ResizeObserver element Interface

You can observe document.body.

new ResizeObserver(() => {
  console.log('resized')
}).observe(document.body)

Can ResizeObserver listen just to width change?

Answer: There isn’t a built-in function, but you can make a wrapper that checks if (only) the width has changed:

const ro = function($el, cb) {
  let last = $el.getBoundingClientRect();
  const observer = new ResizeObserver(function() {
    const data = $el.getBoundingClientRect();
    if(data.width !== last.width && data.height === last.height)
      cb();
    last = data;
  });
  observer.observe($el);
}

Then use it like:

ro(layout.current, setLayout);

Source: stackoverflow.com

Here’s an example. Read more documentation at https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver.

function handleWidthChange (width) {
  console.log(width);
}

let prevWidth = 0;

const observer = new ResizeObserver(entries => {
  for (const entry of entries) {
    const width = entry.borderBoxSize?.[0].inlineSize;
    if (typeof width === 'number' && width !== prevWidth) {
      prevWidth = width;
      handleWidthChange(width);
    }
  }
});

observer.observe(document.body, {box: 'border-box'});

Do comment if you have any doubts or suggestions on this JS event topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *