Created
March 7, 2023 13:36
-
-
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
This file contains 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
(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