I want to check <body>'s width change (not height).
Is there a way to do so with ResizeObserver?
I want to check <body>'s width change (not height).
Is there a way to do so with ResizeObserver?
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'});
? in the entry.borderBoxSize?.[0].inlineSize?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.