7

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

Is there a way to do so with ResizeObserver?

1

1 Answer 1

15

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'});
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks very much, may I know what is the meaning of ? in the entry.borderBoxSize?.[0].inlineSize?
It is the optional chaining operator. width will be undefined if that property is not present on the ResizeObserverEntry (rather than throwing a TypeError when trying to access the first array member). If this answers your question, feel free to mark it as such.
thanks. just note that html-minify-terser fails to recognize it. lol

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.