Home > Article > Web Front-end > How Can I Reliably Detect DIV Element Dimension Changes?
Detecting Dimension Changes of DIV Elements
You have encountered difficulties in detecting dimension changes of a DIV element when the browser window is resized. This question explores possible solutions to this problem.
jQuery Resize Event Binding
Your initial approach of binding the callback function to the jQuery resize event on the DIV is incorrect. The resize event is triggered only when the window is resized, not when the dimensions of the DIV change.
Solution: Resize Observer API
A newer solution is the Resize Observer API, which has good browser support. This API allows you to observe changes in the dimensions of an element:
const observer = new ResizeObserver((entries) => { // Code to handle dimension changes }); observer.observe(targetElement);
In the provided HTML sample, you can use the Resize Observer API as follows:
const textbox = document.getElementById('textbox'); const width = document.getElementById('width'); const height = document.getElementById('height'); const observer = new ResizeObserver(() => { width.value = textbox.offsetWidth; height.value = textbox.offsetHeight; }); observer.observe(textbox);
This code will update the width and height outputs when the dimensions of the textbox change.
The above is the detailed content of How Can I Reliably Detect DIV Element Dimension Changes?. For more information, please follow other related articles on the PHP Chinese website!