PDA

View Full Version : Activating CSS Transitions with javascript



Lee
02-12-2013, 06:10 PM
Hello,

I am wondering if it's possible transition something when using javascription document.getElementById() function?

For example, if I use onclick getElementById("Div1").style.width = "100px"; can I make that transition?

Lee.

Tuts
02-12-2013, 10:56 PM
You can do:


#Div1 {
width: 50px;
height: 50px;
border: 1px solid red;
-webkit-transition: width 1s ease-in;
}




var element = document.getElementById("Div1");
element.style.width = "100px";


No support for IE9 nor Opera Mobile though. (http://caniuse.com/css-transitions)

The example only works in Safari and Chrome (a selected few versions of both).

Applying a cross browser solution is done using similar code to the below:

-webkit-transition: all 0.3s ease-out; /* Chrome 1-25, Safari 3.2+ */
-moz-transition: all 0.3s ease-out; /* Firefox 4-15 */
-o-transition: all 0.3s ease-out; /* Opera 10.50–12.00 */
transition: all 0.3s ease-out; /* Chrome 26, Firefox 16+, IE 10+, Opera 12.10+ */
(Credit css3please (http://css3please.com/)).

If you're animating more than just the width (for example the height), you can modify the CSS transition to animate all instead of width

Anyway, here's the code I just explained above http://jsfiddle.net/3FHX3/

Even better!

Instead of animating certain values, why not just add a class with a width of 100px?

For example, in your CSS you can declare the following:


#Div1.expand {
width: 100px;
}


and then with JavaScript (and still with the CSS3 Transition), add the class using the setAttribute() function like so:


var element = document.getElementById("Div1");
element.setAttribute("class", "expand");


This code can be found here http://jsfiddle.net/3FHX3/1/

Want to hide these adverts? Register an account for free!