Transitions are one of the most exciting and powerful features of CSS3 and when used in conjunction with JavaScript, the simplicity and power of these transitions can be considerably increased. CSS pseudo-classes and media queries represent certain states for certain elements. These states occur after specific events on the page. So naturally, CSS3 transitions can also be fired using any JavaScript event. Let’s try a simple click event that toggles a class name.
The following HTML code is to start with:
1 2 |
<div class="box"></div> <input type="button" value="Let's Do This Thing" id="bt"> |
So we have a box with a class of “box”, and a button. Let’s add the following jQuery:
1 2 3 4 5 |
$(function() { $("#bt").click(function() { $(".box").toggleClass("box-change"); }); }); |
This uses jQuery’s .toggleClass method to add or remove the specified class name. So let’s add the CSS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
.box { width: 300px; height: 300px; -webkit-transition: width 2s ease, height 2s ease; -moz-transition: width 2s ease, height 2s ease; -o-transition: width 2s ease, height 2s ease; -ms-transition: width 2s ease, height 2s ease; transition: width 2s ease, height 2s ease; } .box-change { width: 400px; height: 400px; } |
The transitions are declared on the .box element (using all the necessary vendor prefixes), and they include the use of multiple transitions separated by a comma (in this case transitioning both width and height). So when the button is clicked, after the .box-change class is added, this will trigger the transition. It’s very similar to what you’d normally do with :hover, or :checked, or media queries, or whatever. But in this case the solution involves JavaScript. So basically when CSS3 is used in conjunction with JavaScript, it considerably enhances the ease of programming and the power of animations.