Home > Web Front-end > JS Tutorial > body text

How Can I Reliably Detect DIV Element Dimension Changes?

Patricia Arquette
Release: 2024-11-24 20:51:27
Original
309 people have browsed it

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);
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template