ResizeObserver
Creates a new ResizeObserver that reports changes to the dimensions of an Element's content or border box
Syntax
new ResizeObserver(callback)Parameters
| Parameter | Type | Description |
|---|---|---|
| callback | (entries: ResizeObserverEntry[], observer: ResizeObserver) => void | Function called when observed element resizes |
Return Value
A new ResizeObserver instance
Examples
const observer = new ResizeObserver((entries) => {
for (const entry of entries) {
const { width, height } = entry.contentRect
console.log(`Size: ${width}x${height}`)
}
})
observer.observe(document.querySelector('.container')!)function onResize(el: HTMLElement, callback: (w: number, h: number) => void) {
const observer = new ResizeObserver((entries) => {
const { width, height } = entries[0].contentRect
callback(width, height)
})
observer.observe(el)
return () => observer.disconnect()
}const chart = document.querySelector('.chart')!
const ro = new ResizeObserver((entries) => {
const { width, height } = entries[0].contentRect
redrawChart(width, height)
})
ro.observe(chart)Understanding ResizeObserver
The ResizeObserver method in JavaScript creates a new ResizeObserver that reports changes to the dimensions of an Element's content or border box. It belongs to the ResizeObserver object and is one of the most widely used methods for working with resizeobserver values in modern JavaScript and TypeScript applications.
The method signature is new ResizeObserver(callback). It accepts 1 parameter: callback. When called, it returns a new resizeobserver instance. Understanding when and how to use ResizeObserver() helps you write more expressive, readable code.
Common use cases for ResizeObserver include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like event-intersectionobserver, event-mutationobserver, dom-getboundingclientrect, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for ResizeObserver is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
IntersectionObserverCreates a new IntersectionObserver that asynchronously observes changes in the intersection of a target element with an ancestor element or the viewport
MutationObserverCreates a new MutationObserver that watches for changes being made to the DOM tree
Element.prototype.getBoundingClientRectReturns a DOMRect object providing information about the size of an element and its position relative to the viewport
Related Tools
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.