2

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.

Red Apple
  • 99
  • 6
  • 2
    Does this answer your question? [How to pause and resume CSS3 animation using JavaScript?](https://stackoverflow.com/questions/5804444/how-to-pause-and-resume-css3-animation-using-javascript) – Omri Attiya Apr 03 '20 at 23:54
  • @OmriAttiya I'm not using webkit so I don't think that'll solve it – Red Apple Apr 04 '20 at 00:21
  • @Mr.ZZ I'm not using a tag since it became obsolete – Red Apple Apr 04 '20 at 00:21
  • @RedApple you don't need the webkit prefixes anymore, but that's still the same, JS `style.animationPlayState` and CSS `animation-play-state`. – Kaiido Apr 04 '20 at 02:28

2 Answers2

5

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>
Hans Felix Ramos
  • 4,264
  • 3
  • 16
  • 40
1

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"); } );