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'] });
Example:
$('p').bind('style', function(e) { console.log( $(this).attr('style') ); }); $('p').width(100); $('p').css('color','red');
This will output the following:
width: 100px; color: red;
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!