1

Is there any way to detect when a CSS class is removed from a DOM element?

I have a <ul>, and I need to capture when this <ul class="open"> has its open class removed.

Any way to do this in Angular or jQuery

core
  • 32,451
  • 45
  • 138
  • 193

3 Answers3

1

If you're talking about monitoring when the class attribute changes without any help from whomever is modifying it, then the only way to do that would be to:

  1. Solve your problem entirely with CSS (where the CSS styles will change automatically when a class is removed)

  2. With a MutationObserver (in modern browsers only) where you can register an interest in that particular attribute change. Unfortunately, MutationObservers are not supported in IE before IE 11.

If you are more specific about what exactly you're trying to accomplish and/or what code is changing the classname, then we could probably offer some other ideas too.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

you can write custom directive for this

app.directive("isNotOpen", function(){
  var linkFunction = function(scope, element, attrs){
      scope.$watch(
       function() {
          return element.attr('class'); 
       }, function(){
         if(!element.hasClass("open")){
             scope.$eval(scope.isNotOpen)
         }
      });
  };

  return {
   link: linkFunction
   scope: {isNotOpen: '&'}
  }
})

and you can use is like below

 <div class="open" is-not-open="dosomething()">
harishr
  • 17,807
  • 9
  • 78
  • 125
1

You could $watch the class attribute with a directive like this :

.directive('watchClass', function() {
    return function(scope, element, attrs) {
        scope.$watch(function() {
            return attrs['class']; // Or element.attr('class');
        }, function(newValue, oldValue) {
            // Check for open class removal and do something
        });
    };
});

And then apply that directive to your elements.

<ul class="open" watchClass>

(Note: having anything else than angular torturing your DOM sounds weird to me)

ThSlyu
  • 26
  • 4
  • I wonder if the `attrs['class']` will be updated if the attribute is changed by something other than `$attr.$set()`? – runTarm Jul 25 '14 at 16:42
  • 1
    I had to change it to `return element.attr('class');` to get it to work. – core Jul 25 '14 at 19:41