Detecting When a Web Element Changes Size with ResizeObserver

ResizeObserver is a JavaScript web API that allows you to run code whenever an element’s size changes.

Before getting into the ResizeObserver, let’s first get refreshed on the different boxes HTML elements are made of. A standard element, take a <div> for example, consists of a content box, and border box. The content box, depicted in blue in the image below, consists of all the content within the padding of the element. The border box consists of the border and everything within it.

How it works

In order to use the API, you need to do two things. First, register the callback that is to be run.

var ro = new ResizeObserver( entries => {
for (let entry of entries) {
let cs = window.getComputedStyle(entry.target);
console.log('watching element:', entry.target);
console.log(entry.borderBoxSize[0].inlineSize,' is ', cs.width);
console.log(entry.borderBoxSize[0].blockSize,' is ', cs.height);
}
}

Device-Pixel-Content-Box

As seen earlier, ResizeObserver can also watch for changes to the device pixel (DP) content box. This box visually is the same as content-box, but its dimensions are recorded in physical device pixels rather than CSS pixels, which are what CSS normally uses. Here is a good article going over the difference between the two types of pixels.

Example Usage In sahirvellani.com

I use ResizeObserver for my personal website in order to run some code when the page changes size. Here is how I did it, and how it can be used if you are using React.

const MyComponent = ({ children }) => {
let handleResize = (entries) => {
let width;
if (entries[0].contentBoxSize) {
if (entries[0].contentBoxSize.inlineSize != undefined){
width = entries[0].contentBoxSize.inlineSize;
} else {
width = entries[0].contentBoxSize[0].inlineSize;
}
} else {
width = entries[0].contentRect.width;
}
if (width < 600) {
setIsMobile(true);
} else {
setIsMobile(false);
}
}
useEffect(() => {
let resize_observer = new ResizeObserver(handleResize);
if (ref.current) {
resize_observer.observe(ref.current);
}
}, [ref]);
return (
<div ref={ref}>
...
</div>
)
}

Software Engineer @ Microsoft | Web Platform | Amateur Astrophotographer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store