Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to listen to a "style change" event?

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'); 
like image 226
David Hellsing Avatar asked Jan 28 '10 21:01

David Hellsing


2 Answers

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+.

like image 147
codebox Avatar answered Sep 18 '22 02:09

codebox


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.

like image 41
Josh Stodola Avatar answered Sep 18 '22 02:09

Josh Stodola