czArek czArek - 19 days ago 7
HTML Question

Listen to change class name of button

I want write JavaScript code which should listen to change class name of element from DOM and execute function as below...

function(){
console.log("Catch class name change!");
}


I have button...

<button class="btn-large red" data-bind="text: submitLabel, trueClick: submit,
css: { 'light-skin': ff.DealTicket.useLightSkin, disabled: !isValid() || isOrderPending() ||isSubmitting(), blue: isBuy(), red: !isBuy(), yellow: isOCO() }">Place Sell Trade</button>


...which changes own class name from

<button class="btn-large red">...


to

<button class="btn-large red dissabled">...


I get this button by

document.querySelector('btn-large.red');


How can I listen to change this name class value ?

I try using eventListener and DOMCOntentLoad, DOMSubtreeModified and it not works.

document.querySelector("btn-large.red").addEventListener("DOMContentLoaded", function(){
console.log("Catch class name change!");
});

Answer

You can use a mutation observer to listen to changes to the element's attributes; when a class is added/removed, the class attribute is updated.

Example:

// The function to call when the class changes
function classChanged(b) {
  console.log("The class changed: " + b.className);
}

// The button
var btn = document.getElementById("the-button");
console.log("Initial class: " + btn.className);

// The mutation observer
var ob = new MutationObserver(function() {
   classChanged(btn);
});
ob.observe(btn, {
  attributes: true,
  attributeFilter: ["class"]
});

// Just for our example, something to periodically modify
// the classes on the button
var timer = setInterval(function() {
  btn.classList.toggle("fuzz");
  btn.classList.toggle("bizz");
}, 500);
setTimeout(function() {
  console.log("Done");
  clearInterval(timer);
}, 10000);
.foo {
  color: blue;
}
.bar {
  color: green;
}
<button id="the-button" class="foo fuzz">This is the button</button>

Comments