Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed Issue #1346 child node selection, added last word handling, removed u… #1350

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions 4-typing-game/solution/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ const quoteElement = document.getElementById('quote');
const messageElement = document.getElementById('message')
const typedValueElement = document.getElementById('typed-value');

// Check if UI elements exist
if (!quoteElement || !messageElement || !typedValueElement) {
console.error("One or more required elements are missing from the DOM.");
}

document.getElementById('start').addEventListener('click', function () {
// get a quote
const quoteIndex = Math.floor(Math.random() * quotes.length);
Expand All @@ -31,11 +36,11 @@ document.getElementById('start').addEventListener('click', function () {

// UI updates
// Create an array of span elements so we can set a class
const spanWords = words.map(function(word) { return `<span>${word} </span>`});
const spanWords = words.map(word => `<span>${word}</span>`);
// Convert into string and set as innerHTML on quote display
quoteElement.innerHTML = spanWords.join('');
// Highlight the first word
quoteElement.childNodes[0].className = 'highlight';
quoteElement.children[0].className = 'highlight';
// Clear any prior messages
messageElement.innerText = '';

Expand All @@ -62,18 +67,20 @@ typedValueElement.addEventListener('input', (e) => {
const elapsedTime = new Date().getTime() - startTime;
const message = `CONGRATULATIONS! You finished in ${elapsedTime / 1000} seconds.`;
messageElement.innerText = message;

typedValueElement.disabled = true;
} else if (typedValue.endsWith(' ') && typedValue.trim() === currentWord) {
// end of word
// clear the typedValueElement for the new word
typedValueElement.value = '';
// move to the next word
wordIndex++;
// reset the class name for all elements in quote
for (const wordElement of quoteElement.childNodes) {
for (const wordElement of quoteElement.children) {
wordElement.className = '';
}
// highlight the new word
quoteElement.childNodes[wordIndex].className = 'highlight';
quoteElement.children[wordIndex].className = 'highlight';
} else if (currentWord.startsWith(typedValue)) {
// currently correct
// highlight the next word
Expand Down