JavaScript: gestire le animazioni CSS infinite

JavaScript: gestire le animazioni CSS infinite

Esiste una soluzione molto semplice per gestire le animazioni CSS infinite con JavaScript.

Dato il seguente codice CSS:


@keyframes grow {
	0% {
		width: 100px;
		height: 100px;
	}
	
	100% {
		width: 120px;
		height: 120px;
	}
}

#animated {
	width: 100px;
	height: 100px;
	background: silver;
	animation: grow 1s infinite;
}

possiamo usare la seguente classe:


#animated.stop {
	animation-name: none;
}

Quindi con JavaScript:


const animated = document.querySelector('#animated');

animated.classList.add('stop'); // Interrompe l'animazione
animated.classList.remove('stop'); // Fa ripartire l'animazione

Torna su