I have been trying to create a wordle-type game, but I don’t know how to get the user input from the contenteditable div’s. What I want to happen is if the user inputs the letter ‘a’ for example, the letter in the div would turn green, whilst the other letters in the other div’s are a different color.
So basically, when the user is done typing in every letter for a guess, they would click enter and the letter ‘a’ would turn green. (The word in this case would be absolute) Also if possible making sure the user actually fills out all the boxes in the row before making the function possible.
let word = "absolute"; function inputFunc() { event.target.nextElementSibling.focus(); } document.getElementById('amo1').addEventListener('keypress', function(e) { document.getElementById('amo1').value = this.innerHTML; });
Here is my full code in JSFiddle, including all the divs, CSS, HTML and JS code: https://jsfiddle.net/Infui/c7q30gez/1/
Advertisement
Answer
https://codepen.io/codmitu/pen/LYegzNN?editors=0011
html:
<p>absolute</p> <div contenteditable="true" style="border: 5px solid; padding: 5px"></div> <button>check</button>
js:
const pText = document.querySelector("p").innerText const div = document.querySelector("div") const button = document.querySelector("button") button.addEventListener("click", () => { const text = div.textContent //checking for numbers if (text.match(/d/gi)) { div.innerText = text return } div.innerHTML = "" text.split("").forEach(letter => { if (pText.includes(letter)) { div.innerHTML += `<span style="color: green">${letter}</span>` } else { div.innerHTML += `<span style="color: grey">${letter}</span>` } }) }) //blur the div if text is longer than 8 letters div.addEventListener("keydown", (e) => { if (div.innerText.length > 7 || e.keyCode == 32) { div.blur() } }) //clear on focus div.addEventListener("focus", () => { div.innerHTML = "" })