<h1>Play/pause CSS animations with JavaScript</h1>
<button id="js-toggle" class="btn" type="button">JS: Toggle animations using `animationPlayState`</button>
<div class="circle a-slide" data-animation="stop">I will play/pause</div>
<div class="circle a-slide" data-animation="once" style="--bgc:tomato;--animdel:250ms;">I will play/pause</div>
<div class="circle a-slide" data-animation="slow" style="--bgc:tan;--animdel:500ms;">I will play/pause</div>
<div class="circle a-slide" data-animation style="--bgc:orange;--animdel:750ms;">I will play/pause</div>
<div class="circle a-pulse" data-animation="alternate" style="--bgc:purple;">I will play/pause</div>
body {
font-family: ui-sans-serif, sysetm-ui, sans-serif;
margin: 0 auto;
max-width: 60rem;
padding: 2rem;
}
.btn {
background-color: cornflowerblue;
border: 0;
border-radius: 0.25rem;
color: #FFF;
display: inline-block;
margin-block-end: 0.5rem;
padding: 1rem;
}
.hidden {
clip: rect(1px 1px 1px 1px);
clip: rect(1px, 1px, 1px, 1px);
clip-path: inset(1px);
display: block;
height: 1px;
overflow: hidden;
position: absolute;
white-space: nowrap;
width: 1px;
}
.circle {
--bgc: cornflowerblue;
--w: 150px;
align-items: center;
background-color: var(--bgc);
border-radius: 50%;
color: #FFF;
display: flex;
height: var(--w);
justify-content: center;
margin-bottom: 1rem;
width: var(--w);
}
.a-pulse {
--animdur: 1s;
--animn: pulse;
will-change: transform;
}
.a-slide {
--animdur: 3s;
--animn: slide;
}
[data-animation] {
animation: var(--animn, none) var(--animdur, 0s) var(--animtf, linear) var(--animdel, 0s) var(--animic, infinite) var(--animdir, alternate) var(--animfm, none) var(--animps, running);
}
/* KEYFRAMES */
@keyframes opacity {
0% {
opacity: 1;
}
50% {
opacity: 0.6;
}
100% {
opacity: 1;
}
}
@keyframes pulse {
0% {
transform: scale(1);
}
25% {
transform: scale(.9);
}
50% {
transform: scale(1);
}
75% {
transform: scale(1.1);
}
100% {
transform: scale(1);
}
}
@keyframes slide {
from { margin-left: 0%; }
to { margin-left: calc(100% - var(--w, 150px)); }
}
/* Toggle Animations */
const jstoggle = document.getElementById('js-toggle');
jstoggle.addEventListener('click', () => {
const animations = document.querySelectorAll('[data-animation');
animations.forEach(animation => {
const running = animation.style.animationPlayState || 'running';
animation.style.animationPlayState = running === 'running' ? 'paused' : 'running';
})
});
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.