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
JavaScript
x
3
1
<div id="mydiv" aria-highlight="false" style="background: red; height: 100px; width: 100px"></div>
2
<label for="highlight"><input type="checkbox id="highlight">Highlight Div</label>
3
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.
JavaScript
1
21
21
1
// Our two elements
2
let square = document.querySelector("#mydiv")
3
let chk = document.querySelector("#highlight")
4
5
// Checkbox click handler
6
chk.addEventListener("click", function(){
7
square.setAttribute("aria-highlight",this.checked)
8
})
9
10
// That is the function called when there is a mutation event
11
var callback = function(mutationsList) {
12
for(var mutation of mutationsList) {
13
if (mutation.type == 'attributes') {
14
console.log("The attribute '" + mutation.attributeName + "' was modified.");
15
}
16
}
17
};
18
19
// The mutation observer
20
var observer = new MutationObserver(callback);
21
observer.observe(square, { attributes: true });
JavaScript
1
2
1
<div id="mydiv" aria-highlight="false" style="background: red; height: 100px; width: 100px"></div>
2
<label for="highlight"><input type="checkbox" id="highlight">Highlight Div</label>