jQuery: start and stop CSS animations

jQuery: start and stop CSS animations

How to start and stop CSS animations with jQuery.

CSS animations are bound to elements with the animation-name property. As the W3C specifications state, "once an animation has started it continues until it ends or the animation-name is removed". By knowing this, we can actually start and stop CSS animations with jQuery.

Suppose that we have the following infinite CSS animation:


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

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

The solution is simple and consists of a specialized CSS class that removes the animation from the selected element:


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

Toggling animations with jQuery is a simple matter of adding and removing a CSS class:


(function( $ ) {
	$(function() {
		$( "#stop" ).click(function() {
			$( "#animated" ).addClass( "off" );
		});
		$( "#start" ).click(function() {
			$( "#animated" ).removeClass( "off" );
		});
	});

})( jQuery );

[view-example url="http://codepen.io/gabrieleromanato/pen/jEfbn"]