ResizeObserver Sample

Available in Chrome 54+ | View on GitHub | Browse Samples

Background

The ResizeObserver API provides an API to get notified whenever an element changes its size.

This sample illustrates how to use ResizeObserver to implement [media query](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries) -like behavior on a per-element basis.

The Google Developers Web Updates article provides more details on ResizeObserver. As of Chrome 54, it is behind the `chrome://flags/#enable-experimental-web-platform-features` flag.

Live Output

On browsers that support ResizeObserver, you should see the border radius of the second box change when resizing the window.


JavaScript Snippet

/* global ResizeObserver */

const ro = new ResizeObserver(entries => {
for (let entry of entries) {
entry.target.style.borderRadius = Math.max(0, 250 - entry.contentRect.width) + 'px';
}
});
// Only observe the 2nd box
ro.observe(document.querySelector('.box:nth-child(2)'));