Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to change a HTML element's colour then fade it back to the original colour

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

.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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading