Misha Kogan
Misha Kogan

Reputation: 27

How to bind classChange in jQuery?

How to bind classChange in jQuery? I need to when one class change, change other class.

I have this function, but this functon run only one time at the web-site load. I need to make a event listener. Can someone help me?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
function switchClass() {
    if($("#sidebar").hasClass('pin-top')){
         $('#sidebar').removeClass('s2');
    }   
    else if($("#sidebar").hasClass('pinned')) {
         $('#sidebar').addClass('s2');
    } 
}

Upvotes: 1

Views: 1096

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075129

There is no "class change" event. On modern browsers, you can use mutation observers to watch for changes to attributes (including class) on elements, and respond to those. On slightly older browsers you can use a library that emulates mutation observers with the old, deprecated mutation events. (Just search for "mutation observer emulation".) On older browsers than that, you have to poll.

// Watch for changes
var ob = new MutationObserver(function() {
  // The class *may* have changed, handle it
});
ob.observe($("#sidebar")[0], {
  attributes: true
});

Here's a mutation observer example:

// Once a second, add or remove the 'foo' class, Just so we have
// something to respond to. Stop after 10.
var counter = 0;
var timer = setInterval(function() {
  $("#sidebar").toggleClass("foo");
  if (++counter >= 10) {
    $("<p>Done</p>").appendTo(document.body);
    clearInterval(timer);
  }
}, 1000);

// Watch for changes
var ob = new MutationObserver(function() {
  $("<p>").html("It " + ($("#sidebar").hasClass("foo") ? "does" : "does not") + " have the foo class").appendTo(document.body);
});
ob.observe($("#sidebar")[0], {
  attributes: true
});
.foo {
  color: blue;
}
<div id="sidebar">I'm the 'sidebar' element</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Upvotes: 5

Related Questions