How to Detect Change in Element Size with Javascript

javascript
Published on May 11, 2020

Checking an element for change in its width or height can be done with the ResizeObserver Javascript object.

ResizeObserver is now supported in all modern browsers.

Example

Try resizing the below <textarea> element.

HTML & Javascript

<textarea id="demo-textarea" readonly></textarea>
const resize_ob = new ResizeObserver(function(entries) {
	// since we are observing only a single element, so we access the first element in entries array
	let rect = entries[0].contentRect;

	// current width & height
	let width = rect.width;
	let height = rect.height;

	console.log('Current Width : ' + width);
	console.log('Current Height : ' + height);
});

// start observing for resize
resize_ob.observe(document.querySelector("#demo-textarea"));

If there is need to stop detecting resize, the unobserve() method can be called.

// end resize observation
resize_ob.unobserve(document.querySelector("#demo-textarea"));
In this Tutorial