HTML5 and CSS3, Second Edition

(singke) #1

Handling Transitions with jQuery


When we select a text box, we want the same fade effect, and we can achieve
that with jQuery’s animate() method. We have to use two events, though; when
the field gets focus we want it to fade to yellow, and when it loses focus we
want it to go back to white. Here’s how we do it:

css3_animation/javascripts/form.js
varaddTransitionFallbackListeners=function(){
$(".logininput[type=email],.logininput[type=password]").focus(function(){
$(this).animate({
backgroundColor:"#ffe"
}, 300 );
});
$(".logininput[type=email],.logininput[type=password]").blur(function(){
$(this).animate({
backgroundColor:"#fff"
}, 300 );
});
};

We define these callbacks inside of a function and then we use Modernizr to
detect support for transitions, load the jQuery color plug-in if the browser
doesn’t support transitions, and then call the function that defines the
callbacks:

css3_animation/javascripts/form.js
Modernizr.load(
{
test:Modernizr.csstransitions,
nope:"javascripts/jquery.color-2.1.2.min.js",
callback:function(url,result){
if(!result){
addTransitionFallbackListeners();
}
}
}
);

And with that we have the transitions working. It’s pretty easy to add support
for transitions thanks to jQuery. Now on to the animations.

Handling the Animations with jQuery
We can make the form shake using jQuery’s animate() function. In javascripts/form.js
we define a new function called addFormSubmitWithFallback() that handles the form
submission, calls our existing processLogin() method, and defines a fail() callback
—just like we did before, except this time we use jQuery to animate the box.

report erratum • discuss

Making Things Move with Transitions and Animations • 177


Download from Wow! eBook <www.wowebook.com>

Free download pdf