0

I am trying to observe a change to

<div id="one" class="elem" data-result="inr"></div>

data-result attribute in this div.

Most of the older methods seem to have been depreciated. I realised that MutationObserver is the best way to proceed. and wrote one on my own which did not work. I found the onattrchange.js which is similar.

With this I am trying to solve the problem I face.

I have created this jsfiddle which is able to detect input changes (using $(document).on), but not the changes to data-result attribute.

I have tried two ways... (1) ('body').attrchange (2) $(document).on('attrchange',...)

I am not sure why this does not work. ( I am also pretty new to js and jquery, learning by coding)

edit: I have found a similar fiddle which does exactly what I want to. I am doing something similar but I guess I have made some small mistake.

abcd
  • 171
  • 1
  • 2
  • 11
  • Why not just use `trigger` to manually raise an event when you change the `data` attribute? – Rory McCrossan Oct 16 '13 at 13:24
  • In the jsfiddle, I am using an input box for testing. In my application the data-result will be modified using jQuery. – abcd Oct 16 '13 at 13:27
  • You may like this link http://stackoverflow.com/questions/240592/is-it-possible-to-listen-for-changes-to-an-objects-attributes-in-javascript - see the very first answered question. – davidkonrad Oct 16 '13 at 13:30
  • This link is interesting. I am trying to understand and add it to my jsfiddle to see if it works in my case. – abcd Oct 16 '13 at 13:43

2 Answers2

0

I found the problem with the code.

The onattrchange.js does not seem to identify changes made using

$("element").data("result",$(this).val());

It detects

$("element").attr("data-result",$(this).val());

I have added the working fiddle.

abcd
  • 171
  • 1
  • 2
  • 11
0

I was looking for same solution, but didn't wanted to use any 3rd party library. After digging out little bit on google as well as on this site, I found solution on https://stackoverflow.com/a/58501827/6879925

// code to change image src in each 1000ms.
count = 0;
setInterval(function () {
    var sourceElement = document.querySelector('#div1');
    sourceElement.setAttribute('data-src', 'something' + count);
    sourceElement.innerHTML = 'something' + count;
    count++;
}, 2000);

function startMutationObserver(tNode, c) {
    // Select the node that will be observed for mutations
    const targetNode = tNode ? tNode : document;

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

    // Callback function to execute when mutations are observed
    const callback = function (mutationsList, observer) {
        for (let mutation of mutationsList) {
            if (mutation.type === 'childList') {
                targetNode.dispatchEvent(new CustomEvent('newChild', {
                    detail: mutation
                }));
            } else if (mutation.type === 'attributes') {
                targetNode.dispatchEvent(new CustomEvent('attributeChange', {
                    detail: mutation
                }));
            }
        }
    }
    // 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();
}
// call this function to start observing DOM element change
startMutationObserver(document);

// code to listen custom event and filter custom event as per requirement
document.addEventListener('attributeChange', function (e) {
    // console.log(e);
    const ele = e.detail;

    if (ele.target.matches('div[data-src]') && ele.attributeName == 'data-src') {

        var src = e.detail.target.getAttribute('data-src');

        console.log('new src=', src);

    }
});
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <div id='div1' data-src="something">Something....</div>
</body>

</html>

I think this is one of the best solution I ever got for attribute change detection in HTML/javaScript.

Anshuk
  • 1
  • 3
  • Welcome to SO, posing link only answers can not be consider as a valid answer, please provide a sample code to show how the problem can be solved. – Saeed Zhiany Oct 23 '19 at 06:53
  • @SaeedZhiany, thanks for you suggestion, Added sample code too in the answer. – Anshuk Oct 23 '19 at 07:27