ResizeObserver not detected. Demo will not work.

Resize Observer component demo

The canonical use case for ResizeObserver is an HTML component whose contents change depending on its size.

Without ResizeObserver API detecting changes is problematic. There are many hacks, but there is no performant, clean, way for component to detect changes to its size.

With ResizeObserver API, ResizeObserver.observe() is all that is needed.

Example 1: Tiled map

Tiled map is a map that uses tiles to fill its content area. The number of tiles depends on content size. Resize the window to force map to change number its tiles.

Code is straightforward:

function handleMapResize(entry) {
  let TileWidth = 100;
  let TileHeight = 100;
  let columnCount = Math.ceil(entry.contentRect.width / TileWidth);
  let rowCount = Math.ceil(entry.contentRect.height / TileHeight);
  // Add/remove tiles. View source for full example.
}
let ro = new ResizeObserver( entries => {
  for (entry of entries)
    if (entry.target.handleResize)
      entry.target.handleResize(entry);
});
for (el of Array.from(document.querySelectorAll('.resizeable-map'))) {
  el.handleResize = handleMapResize;
  ro.observe(el);
}