Firing events on CSS class changes in jQuery

后端 未结 13 862
天涯浪人
天涯浪人 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 05:03

    You can bind the DOMSubtreeModified event. I add an example here:

    HTML

    <div id="mutable" style="width:50px;height:50px;">sjdfhksfh<div>
    <div>
      <button id="changeClass">Change Class</button>
    </div>
    

    JavaScript

    $(document).ready(function() {
      $('#changeClass').click(function() {
        $('#mutable').addClass("red");
      });
    
      $('#mutable').bind('DOMSubtreeModified', function(e) {
          alert('class changed');
      });
    });
    

    http://jsfiddle.net/hnCxK/13/

    0 讨论(0)
  • 2020-11-22 05:06

    if you know a what event changed the class in the first place you may use a slight delay on the same event and the check the for the class. example

    //this is not the code you control
    $('input').on('blur', function(){
        $(this).addClass('error');
        $(this).before("<div class='someClass'>Warning Error</div>");
    });
    
    //this is your code
    $('input').on('blur', function(){
        var el= $(this);
        setTimeout(function(){
            if ($(el).hasClass('error')){ 
                $(el).removeClass('error');
                $(el).prev('.someClass').hide();
            }
        },1000);
    });
    

    http://jsfiddle.net/GuDCp/3/

    0 讨论(0)
  • 2020-11-22 05:08

    Whenever you change a class in your script, you could use a trigger to raise your own event.

    $(this).addClass('someClass');
    $(mySelector).trigger('cssClassChanged')
    ....
    $(otherSelector).bind('cssClassChanged', data, function(){ do stuff });
    

    but otherwise, no, there's no baked-in way to fire an event when a class changes. change() only fires after focus leaves an input whose input has been altered.

    $(function() {
      var button = $('.clickme')
          , box = $('.box')
      ;
      
      button.on('click', function() { 
        box.removeClass('box');
        $(document).trigger('buttonClick');
      });
                
      $(document).on('buttonClick', function() {
        box.text('Clicked!');
      });
    });
    .box { background-color: red; }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div class="box">Hi</div>
    <button class="clickme">Click me</button>

    More info on jQuery Triggers

    0 讨论(0)
  • 2020-11-22 05:08

    change() does not fire when a CSS class is added or removed or the definition changes. It fires in circumstances like when a select box value is selected or unselected.

    I'm not sure if you mean if the CSS class definition is changed (which can be done programmatically but is tedious and not generally recommended) or if a class is added or removed to an element. There is no way to reliably capture this happening in either case.

    You could of course create your own event for this but this can only be described as advisory. It won't capture code that isn't yours doing it.

    Alternatively you could override/replace the addClass() (etc) methods in jQuery but this won't capture when it's done via vanilla Javascript (although I guess you could replace those methods too).

    0 讨论(0)
  • 2020-11-22 05:10
    var timeout_check_change_class;
    
    function check_change_class( selector )
    {
        $(selector).each(function(index, el) {
            var data_old_class = $(el).attr('data-old-class');
            if (typeof data_old_class !== typeof undefined && data_old_class !== false) 
            {
    
                if( data_old_class != $(el).attr('class') )
                {
                    $(el).trigger('change_class');
                }
            }
    
            $(el).attr('data-old-class', $(el).attr('class') );
    
        });
    
        clearTimeout( timeout_check_change_class );
        timeout_check_change_class = setTimeout(check_change_class, 10, selector);
    }
    check_change_class( '.breakpoint' );
    
    
    $('.breakpoint').on('change_class', function(event) {
        console.log('haschange');
    });
    
    0 讨论(0)
  • 2020-11-22 05:11

    Just a proof of concept:

    Look at the gist to see some annotations and stay up-to-date:

    https://gist.github.com/yckart/c893d7db0f49b1ea4dfb

    (function ($) {
      var methods = ['addClass', 'toggleClass', 'removeClass'];
    
      $.each(methods, function (index, method) {
        var originalMethod = $.fn[method];
    
        $.fn[method] = function () {
          var oldClass = this[0].className;
          var result = originalMethod.apply(this, arguments);
          var newClass = this[0].className;
    
          this.trigger(method, [oldClass, newClass]);
    
          return result;
        };
      });
    }(window.jQuery || window.Zepto));
    

    The usage is quite simple, just add a new listender on the node you want to observe and manipulate the classes as usually:

    var $node = $('div')
    
    // listen to class-manipulation
    .on('addClass toggleClass removeClass', function (e, oldClass, newClass) {
      console.log('Changed from %s to %s due %s', oldClass, newClass, e.type);
    })
    
    // make some changes
    .addClass('foo')
    .removeClass('foo')
    .toggleClass('foo');
    
    0 讨论(0)
提交回复
热议问题