Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop css animation in current position on hover?

I have a div inside which moves another div. I need to stop .block at the current position when I hover on .container. How to do it?

HTML:

<div class="container">
    <div class="block"></div>
</div>

CSS:

.container {
    width: 200px;
    height: 100px;
    padding: 10px;
    border: 1px solid #000;
    position: relative;
}

.block {
    width: 100px;
    height: 100px;
    background: red;
    position: absolute;
    animation: move 2s linear infinite;
}

@keyframes move {
    0% { left: 10px; }
    25% { left: 50px; }
    50% { left: 100px; }
    75% { left: 50px; }
    100% { left: 10px; }
}

DEMO

like image 829
Ihor Tkachuk Avatar asked Oct 20 '15 13:10

Ihor Tkachuk


3 Answers

You can add

.block:hover
{
    animation-play-state: paused;
}

to pause the animation when you hover over it.

https://developer.mozilla.org/en-US/docs/Web/CSS/animation-play-state

like image 57
Yvo Cilon Avatar answered Sep 20 '22 02:09

Yvo Cilon


You can pause animation when hover on .container. Consider following css:

.container:hover .block{
    animation-play-state: paused;
}

DEMO

like image 32
Manwal Avatar answered Sep 22 '22 02:09

Manwal


CSS:

.container:hover > .block {
    -webkit-animation-play-state:paused;
    -moz-animation-play-state:paused;
    -o-animation-play-state:paused; 
    animation-play-state:paused;
}

JS:

var node = document.getElementsByClassName("block")[0];

node.addEventListener('mouseenter', function(evt) {
    evt.currentTarget.style.webkitAnimationPlayState = 'paused';    
});

node.addEventListener('mouseleave', function(evt) {
    evt.target.style.webkitAnimationPlayState = 'running';  
});
like image 35
Griffith Avatar answered Sep 22 '22 02:09

Griffith