<div>Click me</div>
<a href='#'>Hover over here to pause the animation</a>
div{
background: green;
height: 59px;
width: 100px;
color: white;
text-align: center;
padding-top: 38px;
}
a {
display: block;
background: gray;
float: left;
margin-top: 5px;
color: white;
text-decoration: none;
padding: 5px 7px;
}
function supportsAnimations() {
var b = document.body || document.documentElement,
s = b.style,
p = 'animation',
animationId = 'myAnimation-' + Math.floor(Math.random() * 10000000),
playState = 'animation-play-state',
v = ['Moz', 'Webkit', 'O', 'ms'];
if (typeof s[p] == 'string') {
return {
id: animationId,
prefix: prefix,
animationProperty: p,
playState: playState,
keyframeString: '@keyframes ' + animationId + ' '
}
}
for (var i = 0; i < v.length; i++) {
if (s[v[i] + 'Animation'] !== undefined) {
var prefix = '-' + v[i].toLowerCase() + '-';
return {
id: animationId,
prefix: prefix,
animationProperty: prefix + 'animation',
playState: prefix + playState,
keyframeString: '@' + prefix + 'keyframes ' + animationId + ' '
};
break;
}
}
return false;
}
function addKeyFrameStyle(keyframeCss) {
var $styles = $('style');
if ($styles.length != 0) {
$styles.last().append(keyframeCss)
} else {
$('head').append('<style>' + keyframeCss + '</style>');
}
}
function animate(duration, marginLeft, loop) {
var css3support = supportsAnimations(),
hoverLinkElm = document.getElementsByTagName("a")[0],
elm = this;
//Animation loop str for CSS3
loop = loop ? 'infinite' : '';
//if(false) { //To test jQuery fallback, uncomment this line and comment out next line
if (css3support) {
//change duration to seconds
duration = duration / 1000;
//If loop is infinite than slow down the animation by multiplying duration with 2
if (loop != '') duration = duration * 2;
elm.style[css3support.animationProperty] = css3support.id + ' ' + duration + 's ' + loop + ' linear';
//Add the CSS rules to the head
addKeyFrameStyle(css3support.keyframeString + '{ 50% { margin-left:' + marginLeft + '}}'); //50% { margin-left:0 } }');
//handle mouse over to pause - You can do that just with CSS but this is just an example how can pause or play using JS.
hoverLinkElm.onmouseover = function () {
elm.style[css3support.playState] = 'paused';
}
hoverLinkElm.onmouseout = function () {
elm.style[css3support.playState] = 'running';
}
}
}
//animate the element
document.getElementsByTagName("div")[0].onclick = function () {
animate.apply(this, [2000, '390px', true]);
}
Also see: Tab Triggers