Detecting Style Changes and Getting Their Respective Values

117 Views Asked by At

I am trying to detect style changes in the HTML tag and get the resulting changes. But most the tutorials usually just show how to detect the change but not how to extract the information about the changes.

var variables_observer=new MutationObserver(function(mutations){
 mutations.forEach(function(mutation){
  
  var STYLE = STYLE THAT CHANGED
  var VALUE = STYLE VALUE THAT CHANGED

  console.log(STYLE);
  console.log(VALUE);

 });    
});
var target=document.documentElement;
variables_observer.observe(target,{attributes:true,attributeFilter:['style']});

For example, if I add a variable to my style --size1:100px is added to my style:

Before:

<html>

After:

<html style="--size1:100px">

Console:

--size1
100px

Does mutation give any change data? And what exactly changed and how it changed?

1

There are 1 best solutions below

0
inquirer On

I tried to set the ID for the html tag and immediately set the background color for it. In setTimeout I change the background color and display in the MutationObserver object the type of change, the tag on which they occurred, the new and old color values.

<!DOCTYPE html>
<html style="background-color: pink;" id="elem">
 <head>
  <title>Mutation</title>
 </head>
<body>

<script>

let observer = new MutationObserver(mutationRecords => {
  for(let mutation of mutationRecords) {
  console.log("type---", mutation.type);
  console.log(mutation.target);
  console.log("attributeName---", mutation.attributeName);
  console.log("oldValue---", mutation.oldValue);
  console.log("newValue---", mutation.target.
  getAttribute(mutation.attributeName));
}
});


observer.observe(elem, {
  attributeOldValue: true, 
  attributes:true,
  attributeFilter:['style']
});

function f() {
let element = document.querySelector("#elem");
element.style.backgroundColor = "green";
}

setTimeout(f, 1000);

</script>

</body>
</html>