Created
June 3, 2021 18:47
-
-
Save ddrscott/6b892b133a157efb94328a9f8566247d to your computer and use it in GitHub Desktop.
Helper to watch for DOM elements getting added and saying the contents.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function sayLastChild(selector) { | |
// Select the node that will be observed for mutations | |
const targetNode = document.querySelector(selector); | |
// Options for the observer (which mutations to observe) | |
const config = { attributes: true, childList: true, subtree: true }; | |
// Callback function to execute when mutations are observed | |
const callback = function(mutationsList, observer) { | |
// Use traditional 'for loops' for IE 11 | |
let mutation = mutationsList.pop(); | |
if (mutation.type === 'childList') { | |
console.log("saying:", mutation.target.innerText); | |
window.setTimeout(() => { | |
let ut = new SpeechSynthesisUtterance(mutation.target.innerText); | |
speechSynthesis.speak(ut); | |
}, 0); | |
} | |
}; | |
// Create an observer instance linked to the callback function | |
const observer = new MutationObserver(callback); | |
// Start observing the target node for configured mutations | |
observer.observe(targetNode, config); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example delaying the mutation observation for 2 seconds and matching class starting with something: