Firing events on CSS class changes in jQuery

后端 未结 13 913
天涯浪人
天涯浪人 2020-11-22 04:45

How can I fire an event if a CSS class is added or changed using jQuery? Does changing of a CSS class fire the jQuery change() event?

相关标签:
13条回答
  • 2020-11-22 04:50

    Good question. I'm using the Bootstrap Dropdown Menu, and needed to execute an event when a Bootstrap Dropdown was hidden. When the dropdown is opened, the containing div with a class name of "button-group" adds a class of "open"; and the button itself has an "aria-expanded" attribute set to true. When the dropdown is closed, that class of "open" is removed from the containing div, and aria-expanded is switched from true to false.

    That led me to this question, of how to detect the class change.

    With Bootstrap, there are "Dropdown Events" that can be detected. Look for "Dropdown Events" at this link. http://www.w3schools.com/bootstrap/bootstrap_ref_js_dropdown.asp

    Here is a quick-and-dirty example of using this event on a Bootstrap Dropdown.

    $(document).on('hidden.bs.dropdown', function(event) {
        console.log('closed');
    });
    

    Now I realize this is more specific than the general question that's being asked. But I imagine other developers trying to detect an open or closed event with a Bootstrap Dropdown will find this helpful. Like me, they may initially go down the path of simply trying to detect an element class change (which apparently isn't so simple). Thanks.

    0 讨论(0)
  • 2020-11-22 04:51

    If you need to trigger a specific event you can override the method addClass() to fire a custom event called 'classadded'.

    Here how:

    (function() {
        var ev = new $.Event('classadded'),
            orig = $.fn.addClass;
        $.fn.addClass = function() {
            $(this).trigger(ev, arguments);
            return orig.apply(this, arguments);
        }
    })();
    
    $('#myElement').on('classadded', function(ev, newClasses) {
        console.log(newClasses + ' added!');
        console.log(this);
        // Do stuff
        // ...
    });
    
    0 讨论(0)
  • 2020-11-22 04:52

    IMHO the better solution is to combine two answers by @RamboNo5 and @Jason

    I mean overridding addClass function and adding a custom event called cssClassChanged

    // Create a closure
    (function(){
        // Your base, I'm in it!
        var originalAddClassMethod = jQuery.fn.addClass;
    
        jQuery.fn.addClass = function(){
            // Execute the original method.
            var result = originalAddClassMethod.apply( this, arguments );
    
            // trigger a custom event
            jQuery(this).trigger('cssClassChanged');
    
            // return the original result
            return result;
        }
    })();
    
    // document ready function
    $(function(){
        $("#YourExampleElementID").bind('cssClassChanged', function(){ 
            //do stuff here
        });
    });
    
    0 讨论(0)
  • 2020-11-22 04:55

    There is one more way without triggering an custom event

    A jQuery Plug-in to monitor Html Element CSS Changes by Rick Strahl

    Quoting from above

    The watch plug-in works by hooking up to DOMAttrModified in FireFox, to onPropertyChanged in Internet Explorer, or by using a timer with setInterval to handle the detection of changes for other browsers. Unfortunately WebKit doesn’t support DOMAttrModified consistently at the moment so Safari and Chrome currently have to use the slower setInterval mechanism.

    0 讨论(0)
  • 2020-11-22 04:59

    I would suggest you override the addClass function. You can do it this way:

    // Create a closure
    (function(){
        // Your base, I'm in it!
        var originalAddClassMethod = jQuery.fn.addClass;
    
        jQuery.fn.addClass = function(){
            // Execute the original method.
            var result = originalAddClassMethod.apply( this, arguments );
    
            // call your function
            // this gets called everytime you use the addClass method
            myfunction();
    
            // return the original result
            return result;
        }
    })();
    
    // document ready function
    $(function(){
        // do stuff
    });
    
    0 讨论(0)
  • 2020-11-22 05:02

    using latest jquery mutation

    var $target = jQuery(".required-entry");
                var observer = new MutationObserver(function(mutations) {
                    mutations.forEach(function(mutation) {
                        if (mutation.attributeName === "class") {
                            var attributeValue = jQuery(mutation.target).prop(mutation.attributeName);
                            if (attributeValue.indexOf("search-class") >= 0){
                                // do what you want
                            }
                        }
                    });
                });
                observer.observe($target[0],  {
                    attributes: true
                });
    

    // any code which update div having class required-entry which is in $target like $target.addClass('search-class');

    0 讨论(0)
提交回复
热议问题