Is it possible to create an event listener in jQuery that can be bound to any style changes? For example, if I want to "do" something when an element changes dimensions, or any other changes in the style attribute I could do:
$('div').bind('style', function() { console.log($(this).css('height')); }); $('div').height(100); // yields '100'
It would be really useful.
Any ideas?
UPDATE
Sorry for answering this myself, but I wrote a neat solution that might fit someone else:
(function() { var ev = new $.Event('style'), orig = $.fn.css; $.fn.css = function() { $(this).trigger(ev); return orig.apply(this, arguments); } })();
This will temporary override the internal prototype.css method and the redefine it with a trigger at the end. So it works like this:
$('p').bind('style', function(e) { console.log( $(this).attr('style') ); }); $('p').width(100); $('p').css('color','red');
Things have moved on a bit since the question was asked - it is now possible to use a MutationObserver to detect changes in the 'style' attribute of an element, no jQuery required:
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'] });
The argument that gets passed to the callback function is a MutationRecord object that lets you get hold of the old and new style values.
Support is good in modern browsers including IE 11+.
Since jQuery is open-source, I would guess that you could tweak the css
function to call a function of your choice every time it is invoked (passing the jQuery object). Of course, you'll want to scour the jQuery code to make sure there is nothing else it uses internally to set CSS properties. Ideally, you'd want to write a separate plugin for jQuery so that it does not interfere with the jQuery library itself, but you'll have to decide whether or not that is feasible for your project.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With