Home > Web Front-end > JS Tutorial > How to Detect Changes in CSS Properties with jQuery?

How to Detect Changes in CSS Properties with jQuery?

Mary-Kate Olsen
Release: 2024-10-29 05:26:02
Original
833 people have browsed it

How to Detect Changes in CSS Properties with jQuery?

Mutation Event Detection for CSS Property Changes with jQuery

The need to detect changes in CSS properties often arises in web development. For example, you may want to execute a specific action when an element's display property is altered. However, determining whether the display property or any other CSS property has changed natively in jQuery can be a challenge.

Checking for CSS Property Changes with DOMAttrModified

Fortunately, the DOM Level 2 Events module addresses this need with mutation events. One such event, DOMAttrModified, provides the ability to monitor attribute changes, including style changes.

To use DOMAttrModified, you can implement the following code:

<code class="js">document.documentElement.addEventListener('DOMAttrModified', function(e) {
  if (e.attrName === 'style') {
    console.log('prevValue: ' + e.prevValue, 'newValue: ' + e.newValue);
  }
}, false);

document.documentElement.style.display = 'block';</code>
Copy after login

This code attaches a listener to the root element (document.documentElement) for the DOMAttrModified event. When the style attribute changes, the listener captures the previous and new values.

Alternative for Internet Explorer: propertychange

If you need to support Internet Explorer browsers, you can utilize the "propertychange" event as a fallback to DOMAttrModified. It enables reliable detection of style changes in IE.

Note:

It's important to note that mutation events have been deprecated and may not be supported by all browsers. For a more cross-browser compatible solution, consider using a mutation observer instead.

The above is the detailed content of How to Detect Changes in CSS Properties with jQuery?. 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