I am creating an interactive crossword app with HTML, Vanilla Javascript and CSS.
I want to add a function to check if the currently selected cell/word or entire grid is correct. To show if the user has inputted the correct or incorrect letter into a given element, I want to immediately set the colour of that element to green/red (correct/incorrect) then fade it back to the original colour.
Snippet for the HTML and CSS:
.example {
background-color: whitesmoke;
}
<div id="example">Cell</div>
Pseudo-JavaScript example:
function fade(element) {
if (element has correct value) {
element.style.backgroundColour = "green";
} // otherwise make it red
// Then make it fade back to whitesmoke
}
Anyone have some ideas to achieve this colour fading?
>Solution :
Simply use classList.toggle to add a class if a condition is met. You then can solve this whole thing with CSS-animation that has a 2-second timer and fades back to the initial value:
function fade(element) {
element.classList.toggle('correct', (element.textContent === 'Cell'));
}
fade(document.querySelector('#example'));
.correct {
animation: 2s linear correct;
}
@keyframes correct {
0% {
background-color: green;
}
100% {
background-color: intial;
}
}
<div id="example">Cell</div>