Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect change in value of a DOM custom data attribute in real-time and run a function as the change occurs using js

I am trying to run a simple function each time there is a change in the value of a custom data attribute of a DOM element.

Here is an example below

<div id="myDiv" data-type="type-1">
    <!-- Some Content -->
</div>

In the HTML code above, i have a div with a custom data attribute of data-type with a value which i change using javascript. I would like to fire up a another function when ever the value of the attribute is changed depending on the value it holds.

For instance Using an if-statement(which doesn't work! ๐Ÿ˜’)

var myDiv = document.getElementById("myDiv");
var myDivAttr = myDiv.getAttribute("data-type");

if(myDivAttr == "type-1"){
   typeOneFunction();
}
else if(myDivAttr == "type-2"){
   typeTwoFunction();
}

// and so on...

I hope my question is clear enough๐Ÿ˜‡๐Ÿ˜Š

like image 854
Redemption Okoro Avatar asked Oct 27 '25 05:10

Redemption Okoro


1 Answers

You can achieve this using Mutation Observers

// Select the node that will be observed for mutations
const targetNode = document.getElementById('myDiv');

// Options for the observer (which mutations to observe)
const config = { attributes: true };

// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
    // Use traditional 'for loops' for IE 11
    for(let mutation of mutationsList) {
        if (mutation.type === 'attributes') {
            if(myDivAttr == "type-1"){
              typeOneFunction();
             }
             else if(myDivAttr == "type-2"){
               typeTwoFunction();
             }
        }
    }
};

// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

// Later, you can stop observing
observer.disconnect();

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

I didn't test that code*

like image 129
Volod Avatar answered Oct 28 '25 19:10

Volod