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>
    #container {
      resize: both;
      border: solid gray;
      background-color: lightblue;
      height: 100px;
      width: 300px;
      overflow: auto;

  <div id="container"></div>
    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);




JavaScript ResizeObserver element Interface

You can observe document.body.

new ResizeObserver(() => {

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)
    last = data;

Then use it like:

ro(layout.current, setLayout);


Here’s an example. Read more documentation at

function handleWidthChange (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;

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 *