Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to toggle HTML/CSS animation on hover and on click [duplicate]

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.

like image 398
Red Apple Avatar asked Dec 09 '25 21:12

Red Apple


1 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>
like image 96
Hans Felix Ramos Avatar answered Dec 12 '25 11:12

Hans Felix Ramos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!