How to detect DIV's dimension changed?
Use the ResizeObserver
API to detect changes in a DIV's dimensions. It provides a callback function which can log the new dimensions every time there is a change:
This snippet will keep an eye on a DIV with the ID #divToWatch
, logging its new width and height whenever it's resized. ResizeObserver has wide browser support, but remember to provide a polyfill for the rest.
Code, meet the ResizeObserver API
Utilizing ResizeObserver
is like having a mini Sherlock Holmes inside your web page, constantly keeping an eye on your DIVs' sizes. It's like he's saying, "Dear Watson, the DIV's size just... ahh, elementary my dear!!!"
An example speaks a thousand words
Here’s a sample code to help clarify how ResizeObserver
works:
The no-browser-left-behind policy
Although ResizeObserver has good coverage, some older browsers might not support it. You can use a polyfill for these cases:
Plan B and some enhancements
When ResizeObserver is not suitable or you need extra firepower, consider alternatives and enhancements:
Sir ResizeSensor at your service
ResizeSensor, a knight from the css-element-queries library, can provide a reliable alternative:
Combo power-up: ResizeObserver, window resize events, and MutationObserver
If you need to be extra sure about capturing those pesky size changes, ResizeObserver
, window resize events
, and MutationObserver
can serve as the three musketeers of your codebase:
Save the performance, save the world!
Remember that all these checks and callbacks can slow down your application, so be kind to your performance by using debouncing:
Some tips to make your life easier
A few nuggets of wisdom for implementing these:
Keep your targets in sight
Choose your selectors wisely to avoid unnecessary overhead, especially when juggling with jQuery:
Traps and pitfalls
Avoid using methods like jQuery onresize plugins and setInterval or setTimeout checks that are too old school and unreliable. Let's keep ahead with the modern APIs, shall we?
Visualization
In a game of Ping-Pong, when the ball 🏓 hits either side of the table, the dimensions slightly change due to the force:
The Sensor (👀) is our ResizeObserver, always on standby to detect any dimension changes:
Just like the ResizeObserver, the Ping-Pong Sensor is also always alert for any dimension changes to the table (DIV).
Was this article helpful?