0

Can someone provide me with an example of an HTML div element with an attribute of aria-highlight that changes and notifies the element using the JavaScript observer method? An example would be using a checkbox that toggles the div and changes the background of the div element. I need this done in vanilla JavaScript

Example HTML

<div id="mydiv" aria-highlight="false" style="background: red; height: 100px; width: 100px"></div>
<label for="highlight"><input type="checkbox id="highlight">Highlight Div</label>
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
ONYX
  • 5,679
  • 15
  • 83
  • 146
  • There is no "JavaScript observer method". There are several different types in the browser DOM that implement the observer pattern, like the MutationObserver mentioned in the answer, or the IntersectionObserver type. Please be more specific about what you're talking about. – Heretic Monkey Feb 12 '21 at 04:01
  • 1
    Does this answer your question? [JavaScript: Listen for attribute change?](https://stackoverflow.com/questions/41424989/javascript-listen-for-attribute-change) – Heretic Monkey Feb 12 '21 at 04:11

1 Answers1

1

So below, you have a checkbox with an event handler to toggle the aria-highlight value.

And an observer which triggers on attribute change from the div.

// Our two elements
let square = document.querySelector("#mydiv")
let chk = document.querySelector("#highlight")

// Checkbox click handler
chk.addEventListener("click", function(){
  square.setAttribute("aria-highlight",this.checked)
})

// That is the function called when there is a mutation event
var callback = function(mutationsList) {
 for(var mutation of mutationsList) {
   if (mutation.type == 'attributes') {
    console.log("The attribute '" + mutation.attributeName + "' was modified.");
   }
 }
};

// The mutation observer
var observer = new MutationObserver(callback);
observer.observe(square, { attributes: true });
<div id="mydiv" aria-highlight="false" style="background: red; height: 100px; width: 100px"></div>
<label for="highlight"><input type="checkbox" id="highlight">Highlight Div</label>
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64