Skip to content
Advertisement

Change aria attribute value using JavaScript Observer method

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>

Advertisement

Answer

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>
Advertisement