JAVASCRIPT

Detect Element Dimension Changes with ResizeObserver

Monitor and react to changes in an element's size using the ResizeObserver API, crucial for responsive UI components and dynamic layouts without polling.

document.addEventListener('DOMContentLoaded', () => {
  const resizableElement = document.getElementById('myResizableDiv');
  const sizeDisplay = document.getElementById('sizeDisplay');

  if (resizableElement && sizeDisplay) {
    const resizeObserver = new ResizeObserver(entries => {
      for (let entry of entries) {
        const { width, height } = entry.contentRect;
        sizeDisplay.textContent = `Width: ${width.toFixed(2)}px, Height: ${height.toFixed(2)}px`;
        console.log(`Element ${entry.target.id} resized to W: ${width}, H: ${height}`);
        // Example: Perform layout adjustments based on new size
      }
    });

    resizeObserver.observe(resizableElement);

    // Optional: Disconnect observer when no longer needed
    // setTimeout(() => resizeObserver.unobserve(resizableElement), 5000);
  }
});
How it works: This code snippet shows how to use the ResizeObserver API to detect when an element's dimensions change. It creates an observer that listens for resize events on a specified DOM element. When a resize occurs, the callback function is executed, providing the new `width` and `height` of the observed element. This is highly useful for building responsive components that need to react dynamically to layout shifts without expensive polling mechanisms.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs