In my current code, when the user inputs a color that matches any of the colors in the array, it will add that color class to the main div.
The issue I'm facing is that my else-if statements only run once. If you input the same color again, it won't add that class after running a different color (e.g. black > red > black).
Is there a more efficient way to handle this scenario?
'use strict';
let inputElement = document.getElementById('inpp');
const btn = document.getElementById('btn');
let outputValue = document.getElementById('output');
const bodyEl = document.getElementById('thisBody');
btn.addEventListener('click', (e) => {
// Prevent form from reloading page
e.preventDefault();
let inputValue = inputElement.value;
let favColors = [
'black',
'red',
'blue',
'green',
'yellow',
'pink',
'orange',
'brown',
'white',
'purple'
];
// Handle user input match
if (favColors.includes(inputValue)) {
outputValue.innerHTML = `Awesome choice! ${inputValue} is a great color!`;
} else if (inputValue === '') {
outputValue.innerHTML = `Please enter a color.`;
} else {
outputValue.innerHTML = `Interesting! ${inputValue} is not on my list of favorites.`;
}
// Add color classes based on user input
for(let i=0; i < favColors.length; i++) {
if(favColors[i] === inputValue) {
bodyEl.classList.add(favColors[i]);
break;
}
}
// Clear input value
inputElement.value = '';
});
/* Color classes */
.black {
background-color: black !important;
}
.red {
background-color: red !important;
}
.blue {
background-color: blue !important;
}
.green {
background-color: green !important;
}
.yellow {
background-color: yellow !important;
}
.pink {
background-color: pink !important;
}
.orange {
background-color: orange !important;
}
.brown {
background-color: brown !important;
}
.white {
background-color: white !important;
}
.purple {
background-color: purple !important;
}
<div id="thisBody">
<div class="container">
<div class="content">
<div>
<h1 id="output">What's your favorite color?</h1>
<form id="formy">
<input id="inpp" type="text" placeholder="What's your favorite color?">
<button type="submit" id="btn">Submit</button>
</form>
</div>
</div>
</div>
</div>