Listen for change of class in jquery

jquery on change
jquery on input
jquery detect input value change
jquery form on change
jquery on dom change
jquery on page change
jquery addeventlistener
jquery change input value

Is there a way in jquery to listen for a change to a node's class and then take some action on it if the class changes to a specific class? Specifically, I'm using the jquery tools tabs plugin with the slideshow and as the slideshow is playing, I need to be able to detect when the focus is on a particular tab/anchor so that I can unhide a specific div.

In my specific example, I need to know when:

<li><a class="nav-video" id="nav-video-video7" href="#video7-video">Video Link 7</a></li>

changes to the following with the class "current" added:

<li><a class="nav-video" id="nav-video-video7 current" href="#video7-video">Video Link 7</a></li>

Then I want to unhide a div at that moment.

Thanks!

Here are some other finds that might provide a solution:

  1. Most efficient method of detecting/monitoring DOM changes?
  2. How can I detect when an HTML element’s class changes?
  3. Monitoring DOM Changes in JQuery

And as it was suggested in #2, why not make current a class that is added, rather than a ID, and have the following CSS handle the show/hide action.

<style type='text/css>
    .current{display:inline;}
    .notCurrent{display:none;}
</style>

Might also be worth it to look into .on() in jquery.

How to fire an event on class change using jQuery?, There is no event raised when a class changes. The alternative is to manually raise an event when you programatically change the class: The power of jQuery offers many features to web developers. You can use following script to change class using jQuery. First of all you need to have the jQuery script first

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

$(document).ready(function() {
  $('#changeClass').click(function() {
    $('#mutable').addClass("red");
  });

  $('#mutable').bind('DOMSubtreeModified', function(e) {
    alert('class changed');
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mutable" style="width:50px;height:50px;">sjdfhksfh
  <div>
    <div>
      <button id="changeClass">Change Class</button>
    </div>

.change(), .change( handler )Returns: jQuery. Description: Bind an event handler to the "​change" JavaScript event, <input class="target" type="text" value="Field 1">. The change event occurs when the value of an element has been changed (only works on <input>, <textarea> and <select> elements). The change() method triggers the change event, or attaches a function to run when a change event occurs. Note: For select menus, the change event occurs when an option is selected. For text fields or text areas, the change event occurs when the field loses focus, after the content has been changed.

I know this is old, but the accepted answer uses DOMSubtreeModified, which has now been deprecated for the MutationObserver. Here's an example using jQuery (test it out here):

// Select the node that will be observed for mutations
let targetNode = $('#some-id');

// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: false, subtree: false, attributeFilter: ['class'] };

// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
    for (let mutation of mutationsList) {
        if (mutation.attributeName === "class") {
            var classList = mutation.target.className;
            // Do something here with class you're expecting
            if(/red/.exec(classList).length > 0) {
                console.log('Found match');
            }
        }
    }
};

// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode[0], config);

// Later, you can stop observing
observer.disconnect();

.resize(), first and second variations, and .trigger( "resize" ) in the third. The resize event is sent to the window element when the size of the browser window changes:  Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java and XML.

With anything like this you have essentially two options, callbacks or polling.

Since you possibly can't get an event to be triggered when the DOM mutates in this way (reliably across all platforms) you may have to resort to polling. To be a bit nicer about it, you could try using the requestAnimationFrame api rather than just using something like setInterval natively.

Taking the most basic approach (i.e. using setInterval and assuming jQuery) you might try something like this:

var current_poll_interval;
function startCurrentPolling() {
  current_poll_interval = setInterval(currentPoll, 100);
}
function currentPoll() {
  if ( $('#nav-video-7').hasClass('current') ) {
    // ... whatever you want in here ...
    stopCurrentPolling();
  }
}
function stopCurrentPolling() {
  clearInterval(current_poll_interval);
}

Events, change(). Bind an event handler to the “change” JavaScript event, or trigger that event on an element. Also  jQuery Manipulating CSS. jQuery has several methods for CSS manipulation. We will look at the following methods: addClass() - Adds one or more classes to the selected elements; removeClass() - Removes one or more classes from the selected elements; toggleClass() - Toggles between adding/removing classes from the selected elements

Listen DOM Changes using jQuery - JSFiddle, <div class="document"></div>. JavaScript + jQuery Compat (edge) Tidy. xxxxxxxxxx. 16. 1. // Ignore this it's just there to dynamically add a div to DOM. 2. This method is a shortcut for .on( "change", handler ) in the first two variations, and .trigger( "change" ) in the third. The change event is sent to an element when its value changes. This event is limited to <input> elements, <textarea> boxes and <select> elements. For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.

jQuery Fire event if CSS class changed?, var $node = $('div') // listen to class-manipulation .on('addClass toggleClass from %s to %s due %s', oldClass, newClass, e.type); }) // make some changes . class: A class to search for. An element can have multiple classes; only one of them must match. An element can have multiple classes; only one of them must match. For class selectors, jQuery uses JavaScript's native getElementsByClassName() function if the browser supports it.

jQuery change() Method, Definition and Usage. The change event occurs when the value of an element has been changed (only works on <input>, <textarea> and <select> elements). As most of you avid jQuery developers know, as of jQuery 1.4, .css() allows us to pass a function as the property value. This is handy for returning current CSS values to determine changes.

Comments
  • This [questions][1] answers can help. [1]: stackoverflow.com/questions/6034161/…
  • Google brought me here. I looked at ".on()" but it wasn't clear which event might trigger when a class is added to an element. I'm in a similar situation as the OP, and needed to trigger when a class is added, but I can't bind to the original click event because the plugin calls preventDefault on the click event.
  • It's been a while since I posted this question and quite frankly I forget how I handled it. Using CSS to hide/unhide a div would be the obvious solution but I'm pretty sure that I must have had some additional things going on that prevented me from keeping it that simple. In any case, I chose the @jsuar solution since it included some helpful links.
  • DOMSubtreeModified is deprecated, use MutationObserver instead.
  • See my answer below for MutationObserver example.