Skip to content

Instantly share code, notes, and snippets.

@riivanov
Created March 7, 2023 13:36
Show Gist options
  • Save riivanov/6f7a1c1ab27360fa9e877096bc7a9825 to your computer and use it in GitHub Desktop.
Save riivanov/6f7a1c1ab27360fa9e877096bc7a9825 to your computer and use it in GitHub Desktop.
Sets alt of all images to random word; Watches for image additions, adds input box, changes alt to input value, sets border color
(async function addRandomWordToImgs() {
async function getRandomWord() {
const word = await fetch("https://random-word-api.herokuapp.com/word");
const ary = await word.json();
return ary.shift();
}
async function getAllImgElements() {
return document.querySelectorAll("img");
}
async function assignRandomWord(imgs) {
for (const el of imgs) {
el.setAttribute("alt", await getRandomWord());
}
}
function onTextInput(ev) {
const text = ev.target.value;
this.style.border = "5px solid #ff0000";
this.setAttribute("alt", text);
}
function onImgClick(ev) {
console.log("click", this);
ev.stopPropagation();
ev.stopImmediatePropagation();
const container = document.createElement("div");
const img = this.cloneNode(true);
container.appendChild(img);
const input = document.createElement("input");
input.type = "text";
input.addEventListener("input", onTextInput.bind(img));
container.appendChild(input);
this.parentNode.replaceChild(container, this);
}
let imgs = Array.from(await getAllImgElements());
imgs.map((el) => el.addEventListener("click", onImgClick));
await assignRandomWord(imgs);
document.addEventListener('DOMContentLoaded', function() {
// Select the node that will be observed for changes
const targetNode = document.body;
// Create an observer instance
const observer = new MutationObserver(async (mutationsList) => {
// Iterate over the list of mutations
for (const mutation of mutationsList) {
if (mutation.type === "childList") {
// Iterate over the added nodes
for (const addedNode of mutation.addedNodes) {
// Check if the added node is an img element
if (addedNode.nodeName === "IMG") {
addedNode.addEventListener("click", onImgClick);
await assignRandomWord(Array.from(await getAllImgElements()));
}
}
}
}
});
// Configure and start the observer
const config = { attributes: true, childList: true, subtree: true };
observer.observe(targetNode, config);
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment