Search code examples
javascriptclasshidden

I want to call a function when an element no longer has a specific class (no jquery)


I am making a plugin for a site where I can only use javascript. I want to execute code when il element with id = "gridview" no longer has the "hidden" class. Thank you for your help.

I already tried:

document.getElementById("id="eval_grid_tab"").addEventListener("click", start);  

This is the html

<li id="eval_grid_tab"><a href="#gridview">Tabel</a></li>
<div id="gridview" class="rightsPanel smscTabsPanel hidden" style="height: 795px;">...</div>

Solution

  • To do this you need to use a MutationObserver. It monitors the DOM for changes (like classes being removed / added) and triggers a callback function for you to use anyway you see fit.

    // Select the node that will be observed for mutations
    var targetNode = document.getElementById('gridview');
    
    // Options for the observer (which mutations to observe)
    var config = { attributes: true };
    
    // Callback function to execute when mutations are observed
    var callback = function(mutationsList, observer) {
        for(var mutation of mutationsList) {
            if (mutation.type == 'attributes') {
                // Triggers when an attribute like 'class' is modified
                console.log('The ' + mutation.attributeName + ' attribute was modified.');
            }
        }
    };
    
    // Create an observer instance linked to the callback function
    var observer = new MutationObserver(callback);
    
    // Start observing the target node for configured mutations
    observer.observe(targetNode, config);
    

    Later, you can stop observing with

    observer.disconnect();