HTML and CSS Reference
In-Depth Information
To preserve everyone's sanity, a better solution is to create a class that sets animation-play-state to paused ,
and then use JavaScript to toggle the class on and off. In pause.html, two (extremely) annoying animations are
assigned the class animated . The styles also contain the following class:
.paused {
animation-play-state: paused;
}
The following JavaScript at the foot of the page identifies all elements with the animated class and binds to
them an event handler that toggles the paused class on and off whenever an animated element is clicked:
function toggleAnimations(animated, paused) {
// Exit silently if old browser
if (!document.getElementsByClassName) return;
// Set default class names if no arguments passed to function
if (!paused) var paused='paused';
if (!animated) var animated='animated';
var animations=document.getElementsByClassName(animated);
// Exit silently if classList not supported
if (!animations[0].classList) return;
for (var i=0; i<animations.length; i++) {
animations[i].addEventListener('click', (function(num) {
return function(e) {
this.classList.toggle(paused);
}
})(i), false);
}
}
toggleAnimations();
This defines a JavaScript function called toggleAnimations() and immediately executes it. The function
optionally takes two arguments for the names of the animation and pause classes. If no arguments are passed to
the function, it assigns animated and paused as the default class names.
This JavaScript function relies on an HTmL5 feature called classList , which is supported by the
latest versions of all mainstream browsers, including iE 10. However, it's not supported by versions prior to Safari
5.1, iOS 5.0, or Android 3.0. if you need to support those browsers, use the classList polyfill (helper script) from
https://github.com/eligrey/classList.js . Alternatively, use jQuery's toggleClass() method.
Caution
The animations in pause.html create a constantly expanding and shrinking orange glow behind a heading
and a multicolored box that twirls as it follows a V-shaped path back and forth across the screen (see Figure 21-4 ).
Clicking the heading brings instant relief, but it can be a challenge to catch the multicolored box and bring it to a
halt. Clicking them again starts the madness all over.
 
 
Search WWH ::




Custom Search