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)

Create a ResizeObserver instance: You start by creating a new instance of the ResizeObserver class.

const observer = new ResizeObserver(entries => {
  // Callback function to handle resize changes
});

Observe DOM elements: You then specify which DOM elements you want to observe for size changes using the observe() method.

const targetElement = document.querySelector('.target-element');
observer.observe(targetElement);

Handle resize changes: Whenever the size of the observed elements changes, the callback function you provided to the ResizeObserver constructor is called with an array of ResizeObserverEntry objects.

const observer = new ResizeObserver(entries => {
  entries.forEach(entry => {
    console.log('Element size changed:', entry.target);
    console.log('New size:', entry.contentRect.width, entry.contentRect.height);
  });
});

Stop observing: When you no longer need to observe a particular element, you can call the unobserve() method.

observer.unobserve(targetElement);

Disconnect observer: If you want to stop observing all elements and release resources, you can call the disconnect() method.

observer.disconnect();

The ResizeObserverEntry object contains information about the observed element, such as its size and position. The contentRect property of the entry provides the new dimensions of the element.

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 *