Home > Web Front-end > JS Tutorial > How Can I Detect DIV Dimension Changes in JavaScript?

How Can I Detect DIV Dimension Changes in JavaScript?

Barbara Streisand
Release: 2024-11-28 22:24:11
Original
493 people have browsed it

How Can I Detect DIV Dimension Changes in JavaScript?

Detecting DIV Dimension Changes with JavaScript

While elements within a DIV may reposition during window resizing, the DIV's dimension itself may also change. To monitor these dimension changes, you can utilize various methods.

1. jQuery resize Event (Obsolete)

Previously, you attempted to use the jQuery resize event on the target DIV. However, this method is generally ineffective for divs. It's more suitable for windows/document size changes.

2. Mutation Observer API

A newer approach is the Mutation Observer API, which allows you to observe changes to DOM elements. This can include changes in dimensions. Here's an example:

const element = document.getElementById('test_div');

const observer = new MutationObserver(() => {
  console.log('DIV dimensions have changed');
});

observer.observe(element, { attributes: true, attributeFilter: ['style'] });
Copy after login

3. Resize Observer API (Preferred)

The Resize Observer API specifically targets monitoring changes in dimensions and is supported by modern browsers. Here's how to use it:

const element = document.getElementById('test_div');

const observer = new ResizeObserver(() => {
  console.log('DIV dimensions have changed');
});

observer.observe(element);
Copy after login

When the DIV's dimensions change, the observer will trigger the specified callback function.

The above is the detailed content of How Can I Detect DIV Dimension Changes in JavaScript?. 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