JS if else condition based on if div element changed > then populate data fields

I would like to create a simple if / else statement with JS. That would check if a div element has changed, before populating JSON data fields / variables that pull from dynamically changed HTML.

I do not want to use the DOMSubtreeModified. As it's depreciated..

Below is the started logic, I have. But it looks like I'll have to scrap the DOMSubtreeModified out for a method that is not depreciating.

The question / problem is: How to re-write not using the above depreciated technique, and how to nest my data array, where it will only pull / populate based on first checking my if (condition) Cheers for any pointers.

var element = document.querySelector('.username'); // username div wrapper

//if {

element.addEventListener('DOMSubtreeModified', function() { // detect if div element changes
  var date = new Date();
  var month = date.getUTCMonth() + 1;
  var day = date.getUTCDate();
  var year = date.getUTCFullYear();

  var time = date.toLocaleTimeString();
  var formattedDate = month + '/' + day + '/' + year;

  console.log(time); // 7:01:21 PM
  console.log(formattedDate); // 3/15/2016
}, false);

// change something on element
setTimeout(function() {
  element.dataset.username = 'bar';
}, 3000);

// json object with captured data fields

var NewUserSession = [{ 

    currentusername: $('.username').text(),
    referrer: document.referrer,
    loggedintime: $(formattedDate),

}];

//}
//
//else { 
//
//
//}

Answers


You can use MutationObserver and watch for data-username changes

var element = document.querySelector('.username'); // username div wrapper

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if (mutation.attributeName = 'data-username') {
      var date = new Date();
      var month = date.getUTCMonth() + 1;
      var day = date.getUTCDate();
      var year = date.getUTCFullYear();

      var time = date.toLocaleTimeString();
      var formattedDate = month + '/' + day + '/' + year;

      snippet.log(time); // 7:01:21 PM
      snippet.log(formattedDate); // 3/15/2016
    }
  });
});

var config = {
  attributes: true,
  attributeFilter: ['data-username']
};

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


// change something on element
setTimeout(function() {
  element.dataset.username = 'bar';
}, 1000);
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<div class="username"></div>

Need Your Help