Search code examples
javascriptjqueryshort

Triggering an event when a css value changes


How can I call a function when a specific CSS variable changes (eg: the height of a particular div), using jquery?


Solution

  • There is no "native" solution for this. If you're strictly using jQuery for manipulation of css propertys, a function hook or (duck punshing) is your best shot:

    (function($) {
        var _oldcss = $.fn.css;
        $.fn.css = function() {
            if( typeof arguments[0] === 'string' ) {
                console.log('css property ', arguments[0], ' is about to change for elem: ', this);
            }
    
            return _oldcss.apply(this, arguments);
        };
    }(jQuery));
    

    This of course is incomplete. If arguments[0] is an object you would need to iterate over the key/values. But this is the basic principle.

    The good thing about this solution is, that even .height() will call .css(). So

    $('div:eq(2)').height(55);
    

    would trigger css property height is about to change for elem: [div#custom-header]