AGamePlayer
AGamePlayer

Reputation: 7732

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?

Upvotes: 7

Views: 12517

Answers (1)

jsejcksn
jsejcksn

Reputation: 33929

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

Upvotes: 14

Related Questions