CSS3 property using JavaScript

Course- Javascript >

So you’ve seen how to get a CSS property, but how can you set a CSS3 property using JavaScript when different browsers support different variations of the property (that is, having different prefixes)?

When a browser supports a particular CSS property, it returns a string value when you request the property from a page element. (This will be an empty string if the property has not yet been set.) If your browser doesn’t support the property, the value undefined is returned instead. So you can easily carry out a test before setting a CSS3 property to determine which variant of the property is supported.

Let’s write code that accepts an array of potential CSS3 properties and returns the one supported by the browser.

function getCss3Property(properties){
// loop through all possible property names
for (var i=0; i<properties.length; i++)="" {="" if="" the="" property="" exists="" for="" this="" element="" (properties[i]="" in="" document.documentelement.style)="" return="" associated="" string="" properties[i];="" }="" <="" pre="">

With this we can return the appropriate version of the feature. Let’s see how that might work for the transition used earlier in this section:

//get the correct CSS3 transition property
var myTrans = getCss3Property(['transition', 'MozTransition',
'WebkitTransition',
'msTransition', 'OTransition'])
//set CSS transition for "link1"
document.getElementById("link1").style[myTrans] = "background 0.5s
ease" ;                 
                 

Let’s suppose that I’m using a version of Firefox that doesn’t support the CSS3 transition property, but does support Mozilla’s own version, MozTransition (corresponding to -moz-transition).

When called, the getCss3Property() function will begin to loop through the list of transition properties corresponding to the various vendor types. Having returned a value of undefined for the property transition (as the browser does not support it) it will, on the following trip through the loop, exit the function, returning a string value of MozTransition. We now know which version of the property to set in the following line of code.