Search code examples
javascriptresize-observer

How to use ResizeObserver to check only body's width change in JavaScript?


I want to check <body>'s width change (not height).

Is there a way to do so with ResizeObserver?


Solution

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