简体   繁体   中英

Adding or removing a class to an element dynamically using Mutation Observer

I want to remove a class from an element when a modal pops-up But when I searched online I found DOMNodeInserted and it was working until it went live and the error I got was DOMNodeInserted has been deprecated.
The error I keep getting below enter image description here

CODE WORKING BELOW, but has been deprecated.

    $(document).on('DOMNodeInserted', function(e) {
            if ( $("body").hasClass('modal-open') ) {
                $(".hide-search").hide();  
                // $(".nav-menu").addClass("border-0");
            } else if ($("body").hasClass('modal-open') === false){
                $(".hide-search").show(); 
                // $(".nav-menu").removeClass("border-0");
            }
        });

New code i wanted to Implement but i don't know how to go about it.

let body = document.querySelector('body');
let observer = new MutationObserver(mutationRecords => {
            console.log(mutationRecords); // console.log(the changes)

            // observe everything except attributes
            observer.observe(body, {
            childList: true, // observe direct children
            subtree: true, // and lower descendants too
            characterDataOldValue: true // pass old data to callback
            });
             });
            }
            } 

  • observe() should be outside the callback
  • all you need to observe is the class attribute, nothing else, so there's no need for the extremely expensive subtree:true .
  • the class may include something else so you need to ignore irrelevant changes
new MutationObserver((mutations, observer) => {
  const oldState = mutations[0].oldValue.split(/\s+/).includes('modal-open');
  const newState = document.body.classList.contains('modal-open');
  if (oldState === newState) return;
  if (newState) {
    $('.hide-search').hide();
  } else {
    $('.hide-search').show();
  }
}).observe(document.body, {
  attributes: true,
  attributeFilter: ['class'],
  attributeOldValue: true,
});

I was able to resolve the above problem with this solution

 function myFunction(x) {
            if (x.matches) {
            var body = $("body");
            var observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                if (mutation.attributeName === "class") {
                var attributeValue = $(mutation.target).prop(mutation.attributeName);
                console.log("Class attribute changed to:", attributeValue);
                if(attributeValue == "ng-scope modal-open") {
                    $(".input-group").addClass("removeDisplay");  
                    $(".nav-menu").addClass("hide-nav-menu");
                } else {
                    $(".input-group").removeClass("removeDisplay");  
                    $(".nav-menu").removeClass("hide-nav-menu");
                }
                }
            });
            });
            observer.observe(body[0], {
            attributes: true
            });
            }
            } 
            // Wow It's working.
            var x = window.matchMedia("(max-width: 1240px)")
            myFunction(x) 
            x.addListener(myFunction)

Firstly I used a match media to check if the screen is lesser than 1240px size then I used the mutation along with checking if an attribute class is present, then perform some certain actions based on that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM