1

I need to call a JS function when classname of the HTML file is changed via Javascript/JQuery.

<html xmlns = "http://www.w3.org/1999/xhtml" class = "A">
-
-
-
-
-
</html>

Now the class name A is getting changed on runtime depending on some conditions and whenever this class name is changing, I need to call another JS function.

I am getting the classname from document.documentElement.className/document.documentElement.classList and was trying to add EventListener to achieve this, but could not succeed.

Could you please advise.

Thanks and Regards, Aniket

Aniket
  • 67
  • 1
  • 8

2 Answers2

1

First of all you should fire your function in the same place that you check the conditions. But as I assume this can not be done for some reason and you want to check for DOM changes.

To do that you can use MutationObserver - you will find documentation with examples here: https://developer.mozilla.org/pl/docs/Web/API/MutationObserver I has quite good browser support: http://caniuse.com/#feat=mutationobserver

Example

// select the target node
var target = document.documentElement;

// create an observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log('Fire something here on: ', mutation.type);
  });    
});

// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };

// pass in the target node, as well as the observer options
observer.observe(target, config);

This was done based on the example so may not be perfect but tested and seems to work as you expect.

marcinrek
  • 339
  • 1
  • 8
0

var prevClass=element.className; setInterval(function(){ //check classname==prevClasss }, 1000);

This will check for every 1 sec whether the class name is not same as previous one if its changed you need to implement the necessary steps

Santhosh Kumar
  • 543
  • 8
  • 22