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

Can You Detect Style Changes in Elements Using JavaScript?

Mary-Kate Olsen
Release: 2024-11-11 03:46:02
Original
579 people have browsed it

Can You Detect Style Changes in Elements Using JavaScript?

Listening to Style Changes with MutationObserver

Question:
Is it possible to monitor style changes in an element using an event listener in JavaScript? For instance, could you detect when an element's dimensions alter using jQuery?

Answer:

Yes, MutationObserver is a modern browser API that enables you to observe changes in an element's attributes, including its style.

Implementation:

var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutationRecord) {
        console.log('style changed!');
    });    
});

var target = document.getElementById('myId');
observer.observe(target, { attributes : true, attributeFilter : ['style'] });
Copy after login

Example:

$('p').bind('style', function(e) {
    console.log( $(this).attr('style') );
});

$('p').width(100);
$('p').css('color','red');
Copy after login

This will output the following:

width: 100px;
color: red;
Copy after login

Support:

MutationObserver is widely supported in modern browsers, including IE 11 .

The above is the detailed content of Can You Detect Style Changes in Elements Using 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