Search code examples
cssanimationcss-animationskeyframe

Animation-play-state Reset or Resume


I am working on a hover button with animation. Here's the code:

CodePen

HTML

<a href="" class="more-link"><span>Hover me &rarr;</span></a> 

CSS

.more-link {
    display: inline-block;
    min-height: 2.4em;
    line-height: 2.4;
    color: #000;
    text-decoration: none;
    text-transform: uppercase;
    font-weight: bold;
    position: relative;
    min-width: 8em;
    text-align: center;
}

.more-link span {
    display: block;
    width: 100%;
    height: 100%;
    position: relative;
    box-sizing: border-box;
    padding: 0 1em;
}

@keyframes tl {
    from {
        width: 0%;
    }
    to {
        width: 100%;
    }
}

@keyframes tr {
    from {
        height: 0%;
    }
    to {
        height: 100%;
    }
}

.more-link:before {
    content: ' ';
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    width: 0%;
    height: 1px;
    background: #000;
    animation: tl 400ms ease-in both;
    animation-play-state: paused;
}

.more-link:hover:before {
    animation-play-state: running;
}

.more-link:after {
    content: ' ';
    display: block;
    position: absolute;
    top: 0;
    right: 0;
    width: 1px;
    height: 0%;
    background: #000;
    animation: tr 400ms ease-in 400ms both;
    animation-play-state: paused;
}

.more-link:hover:after {
    animation-play-state: running;
}

.more-link span:before {
    content: ' ';
    display: block;
    position: absolute;
    bottom: 0;
    right: 0;
    width: 0%;
    height: 1px;
    background: #000;
    animation: tl 400ms ease-in 800ms both;
    animation-play-state: paused;
}

.more-link:hover span:before {
    animation-play-state: running;
}

.more-link span:after {
    content: ' ';
    display: block;
    position: absolute;
    bottom: 0;
    left: 0;
    width: 1px;
    height: 0%;
    background: #000;
    animation: tr 400ms ease-in 1200ms both;
    animation-play-state: paused;
}

.more-link:hover span:after {
    animation-play-state: running;
}

As you can see, I have set the animation-play-state: paused anytime I hover out the button but what I really need is a "resume" or "reset" of the animation when I hover out, I was looking some documentation here https://developer.mozilla.org/en-US/docs/Web/CSS/animation-play-state but there is not this implementation. What's the workaround for my case?


Solution

  • Why not used event listeners with Javascript?

    Something like:

    (element).addEventListener("mouseover", function(){
    (Add your animation name and info here that executes ONLY when hovered over.)
    });
    

    Then do this:

    (element).addEventListener("mouseout", function(){
    (Add your animation name and info here that executes ONLY when the mouse leaves the div.)
    });