M-S M-S - 1 month ago 10
HTML Question

How to invoke function once the dom element style is changed Javascript/jquery

I have gone through multiple examples, and implemented the same behavior what the example has stated.

Once the page is loaded, if there is a change in the styling of the dom element I need to trigger a method.

Even if I change anything in the browser console, then also the style change event should trigger. the event will be on display none and display block.

In my code, if am changing in the browser console then the change method is not getting triggered.

This is what I tried:



(function() {
var ev = new $.Event('style'),
orig = $.fn.css;
$.fn.css = function() {
var ret = orig.apply(this, arguments);
$(this).trigger(ev);
return ret;
}
})();


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

p {
display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p> test </p>




Answer

You could use MutationObserver:

Demo:

// create an observer instance
var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        var oldDisplay = (mutation.oldValue + '').match(/display:\s*(\w*)/);
        oldDisplay = oldDisplay ? oldDisplay[1] : '';
        if (oldDisplay !== mutation.target.style.display) {
            console.log('element', mutation.target.id, 
                    'style.display=', mutation.target.style.display);
        }
    });    
});
 
// attach the observer to the elements of interest:
$('p').each(function () {
    observer.observe(this, { 
        attributes: true, 
        attributeFilter: ['style'],
        attributeOldValue: true
    });
});

// test it, by changing style.display through button clicks:
$('button').click(function() {
    $('p').toggle(); // show/hide
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="p1"> test this </p><button>hide/show</button>