Kristian Pospis
Kristian Pospis

Reputation: 39

In jQuery how do you trigger function when dom changes?

I am using a jQuery plugin that adds background--dark background--complex class to text to contrast it from a background, and this changed during scrolling to background--light background--complex for example. I would need to add class to overlay id (dover=dark overlay) (nover=no overlay) (lover=light overlay) depending on what class the plugin has added to the text. I am really not advanced with jQuery, Im not asking you to do it instead of me but you would save me a lot of struggle and I would understand it better...

jQuery(document).ready(function(){

    if(jQuery( "#globaltext" ).hasClass( "background--dark background--complex" )){
        jQuery( "#overlay" ).addClass( "dover" );
    }else{
        jQuery( "#overlay" ).addClass( "nover" );
    }
});

Upvotes: 1

Views: 356

Answers (1)

miladfm
miladfm

Reputation: 1526

I have another solution. you dont need jQuery, just javascript in enough

HTML :

<div id="classList">my Colors</div>

<button onclick="changeClass('red')">red</button>
<button onclick="changeClass('blue')">blue</button>
<button onclick="changeClass('yellow')">yellow</button>

CSS:

.red{
  color:red;
}
.blue{
  color:blue;
}
.yellow{
  color:yellow;
}

for javascript part 1: create EventListener

// create custom EventListener for just attribute
function attributeEventListener(target, attr, fun){
  target = document.querySelector(target);

  var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
      // just looking for our attribute
      if (mutation.attributeName == attr){
        fun();
      }
    });    
  });

  // configuration of the observer:
  //just looking for attributes
  var config = {attributes: true};

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

part 2 - you need to use it like that :

new attributeEventListener('#classList','class', function(){
  console.log('changed ...');
});
// first parameter is target (css selector)
// second parameter is attribute name (for your case is class)
// third parameter is your function when event called ...

part 3 - change class

function changeClass(color){
      var target = document.getElementById('classList');
      if (target.className != color)
        target.className = color; 
    }

see my code here : https://codepen.io/miladfm/pen/qmGEgm

MutationObserver documents: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

Broswer Support: just modern browsers support mutationobserver

Upvotes: 1

Related Questions