DEV Community

Cover image for Fading on click with CSS Transition
Juan Cruz
Juan Cruz

Posted on

Fading on click with CSS Transition

I was getting my hands on this week Scrimba's weekly challenge Dog Years Converter, and I figured I'd make some text fade out and then in when I clicked a button. This button should calculate and make my application show how many dog years old is a human being.

So let's begin. This is my html container with a form, with a number input and a submit button in it:

<div class="container">
    <h1 class="title">Dog Years Converter</h1>
    <form id="myForm" enctype="multipart/form-data">
        <input
            name="humanYears"
            type="number"
            id="humanYearsInput"
            min="0"
            max="150"
            step="1"
            placeholder="Human Years"
            required
        />
        <input type="submit" value="Convert me to dog years!" />
    </form>
    <h3 class="result" id="result"></h3>
</div>   
Enter fullscreen mode Exit fullscreen mode

When I click the submit button, a text should a appear below the form, indicating how many dog years, months and days old are you:

Alt Text

What I wanted, is that the first time I set my human years and clicked the submit button, a fade in effect on the result text (<h1>) kicked in. And the second time I clicked the submit button the text would fade out and then fade in again with the new calculated dog age.

To get this effect going on, what I did was toggle a .fade class on the <h1> result element, wait 500ms for the transition to finish, set the new value, and toggle the .fade class again whenever a submit event was triggered:

document.getElementById('myForm').addEventListener('submit', async (e) => {
  e.preventDefault()

  const formData = Array.from(new FormData(e.currentTarget))

  const numberConversion = Number(formData[0][1])/10.5

  const resultContainer = document.getElementById('result')

  resultContainer.classList.toggle('fade')

  await new Promise(r => setTimeout(r, 500))

  numberConversion > 0 ?
    resultContainer.innerText = `You're ${yearsToYearsMonthsDays(numberConversion)}!`
    :
    resultContainer.innerText = "You're not born yet!"

  resultContainer.classList.toggle('fade')
})
Enter fullscreen mode Exit fullscreen mode

The fading transition is defined in the CSS as follows:

.result {
    opacity: 1;
    transition: opacity 500ms ease-in-out;    
}

.result.fade {
    opacity: 0;    
}
Enter fullscreen mode Exit fullscreen mode

Should you want to checkout the full code, it's available on Scrimba!

Top comments (0)