javascripthtmlcsslayoutreflow

How to listen for layout changes on a specific HTML element?


What are some techniques for listening for layout changes in modern browsers? window.resize won't work because it only fires when the entire window is resized, not when content changes cause reflow.

Specifically, I'd like to know when:


Solution

  • New browsers now have ResizeObserver, which fires when the dimensions of an element's content box or border box are changed.

    const observer = new ResizeObserver(entries => {
      const entry = entries[0];
      console.log('contentRect', entry.contentRect);
      // do other work here…
    });
    
    observer.observe(element);