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');
As others have suggested, if you have control over whatever code is changing the style of the element you could fire a custom event when you change the element's height:
Otherwise, although pretty resource-intensive, you could set a timer to periodically check for changes to the element's height...
I think the best answer if from Mike in the case you can't launch your event because is not from your code. But I get some errors when I used it. So I write a new answer for show you the code that I use.
Extension
Usage
I got error because var ev = new $.Event('style'); Something like style was not defined in HtmlDiv.. I removed it, and I launch now $(this).trigger("stylechanged"). Another problem was that Mike didn't return the resulto of $(css, ..) then It can make problems in some cases. So I get the result and return it. Now works ^^ In every css change include from some libs that I can't modify and trigger an event.
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:
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+.
Just adding and formalizing @David 's solution from above:
Note that jQuery functions are chainable and return 'this' so that multiple invocations can be called one after the other (e.g
$container.css("overflow", "hidden").css("outline", 0);
).So the improved code should be: