How to toggle HTML/CSS animation on hover and on click

Viewed 1271

I am having trouble trying to stop and start animation whenever I hover over the element or on click. This is my HTML element:

<div class='marquee'>
   <h1>Some Text</h1>
</div>

CSS:

.marquee {
    width: 80%;
    white-space: nowrap;
    overflow: hidden;
    box-sizing: border-box;
}

.marquee h1 {
    display: inline-block;
    padding-left: 100%;
    animation: marquee 15s linear infinite;
}

@keyframes marquee {
    0%   { transform: translate(0, 0); }
    100% { transform: translate(-100%, 0); }
}

Right now, the animation just goes on forever by default. How can I have it so that whenever I hover over or click on the h1 or the div, the animation will pause and resume accordingly. I'm assuming to pause/restart the animation on click, I would need a JavaScript function. Any help is appreciated.

2 Answers

You can use animation-play-state rule:

.marquee {
    width: 80%;
    white-space: nowrap;
    overflow: hidden;
    box-sizing: border-box;
}

.marquee h1 {
    display: inline-block;
    padding-left: 100%;
    animation: marquee 15s linear infinite;
}

.marquee h1:hover {
    animation-play-state: paused;
}

@keyframes marquee {
    0%   { transform: translate(0, 0); }
    100% { transform: translate(-100%, 0); }
}
<div class='marquee'>
   <h1>Some Text</h1>
</div>

Or with JS:

function stopAnimation(e){
   if (e.target.style.animationPlayState == ""){
     e.target.style.animationPlayState = "paused";
   } else {
     e.target.style.animationPlayState = "";
   }
}
.marquee {
    width: 80%;
    white-space: nowrap;
    overflow: hidden;
    box-sizing: border-box;
}

.marquee h1 {
    display: inline-block;
    padding-left: 100%;
    animation: marquee 15s linear infinite;
}


@keyframes marquee {
    0%   { transform: translate(0, 0); }
    100% { transform: translate(-100%, 0); }
}
<div class='marquee'>
   <h1 onclick="stopAnimation(event)">Some Text</h1>
</div>

I would suggest using jquery to change the animation property.

$('.marquee').mouseenter(() => { $(this).css("animation: marquee 15s linear infinite"); } );

$('.marquee').mouseleave(() => { $(this).css("animation: none"); } );
Related