Detect width, height changes with Javascript
Use ResizeObserver Web API to detect when an elements dimension changes.
ResizeObserver is a JavaScript API that’s very similar to other observer APIs like the Intersection Observer API. It allows for elements to be notified when their size changes.
Let's say we have a container that we want to observe width and height changes.
First, we have to create a Resize Observer with a callback function to handle dimension changes.
The callback function is called whenever the dimensions of an observed element change. Each change is given as an entries
object which contains contentRect with width & height.
Next, observe container element using ResizeObserver.observe()
method.
End result
All major browsers support Resize Observer
API, with overall support at 92%.
Check out the latest coverage at CanIuse.com/ResizeObserver.
Check out ResizeObserver
documentation on MDN