Simple Button Animation Name Swap


by Jeremy Caudle
code

I wanted to see how difficiult it might be to swap out a button's animation. Turns out it is not as difficult as I anticipated. I learned about the CSSKeyframesRule via MDN today, so I think I'll find a way to make use of it for something like this rather than the approach I took today.

View the code:

HTML and JS
<section class="code-block">
            <button id="disappearBtn">Click to make disappear</button>
        </section>
        <script>
            /* Variables */
            const button = document.getElementById('disappearBtn');

            /* Events */
            button.addEventListener('click', () => {
                button.style.setProperty('animation-name', 'disappear');
            });

        </script>
CSS
@keyframes appear {
                0% {opacity: 0; scale: 0;}
                100% {opacity: 1; scale: 1;}
            }

            @keyframes disappear {
                0% {opacity: 1; scale: 1;}
                100% {opacity: 0; scale: 0;}
            }

            section.code-block {
                width: clamp(16em, 90vw, 60em);
                background-color: slategrey;
                min-height: 3rem;
                margin: 3rem auto;
                display: grid;
                place-items: center;
                padding: 3rem;
            }

            button {
								background-color: white;
                border: 0;
                border-radius: .5rem;
                padding: 1rem 2rem;
                box-shadow: 0 5px 5px 5px rgba(0, 0, 0, 0.125);
                animation-name: appear; animation-delay: 0; animation-timing-function: ease-out; animation-duration: .3s; animation-iteration-count: 1; animation-fill-mode: forwards;
            }