0

I want to run the function below whenever its div parent container <div class="section">...</div> becomes "active" e.g. <div class="section active">...</div>

  $(".skills-grid__col").each(function () {
      var left = $(this).data('left');
      $(this).animate({
          opacity: 1,
          left: left
      }, 1200);
  });

<div class="section">
  <div class="skills-grid__col"></div>
  <div class="skills-grid__col"></div>
</div>

What kind of event should I use in this case?

sdvnksv
  • 9,350
  • 18
  • 56
  • 108
  • possible duplicate of [event trigger on class change](http://stackoverflow.com/questions/10612024/event-trigger-on-class-change) – George Dec 05 '14 at 09:51
  • 1
    Much better is to trigger some event from the code that actually changes class. – dfsq Dec 05 '14 at 09:52
  • If you have access to the event which makes the container "active", put your code in that. – Taha Paksu Dec 05 '14 at 09:52

1 Answers1

2

There's not really a lot you can do with events if you want to support old browsers.

If dropping support for IE10 is OK, then you can use a MutationObserver which will be notified when the element changes :

var observer = new MutationObserver(function(mutations) {
  if ($yourElement.hasClass('active')) {
     // do things
  }
});
observer.observe($yourElement[0], {attributes: true});

If you can't drop IE10, and assuming you don't want to periodically check the element, you'd have to hook the part where the class changes, which is usually the best solution. Of course you could also write a shim by periodically checking the class if window.MutationObserver is undefined.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • I plan to support IE9+, but thanks for the possible solution. Seems like hooking the function to the event where the class changes is the only appropriate solution in this case. Thanks. – sdvnksv Dec 05 '14 at 10:34