Extending the Modernizr.prefixed method

Starting with version 2.0 the awesome feature detection js library Modernizr includes a method called "prefixed". In short, this method will give you the correct prefixed version of a CSS 3 property which still requires this. E.g: -webkit, -moz and so on. Used in conjunction with the jQuery library you can use Modernizr.prefixed for typical tasks like adding a transition to an element in script without having to clutter up your CSS with a gazillion lines of vendor prefixes.

However, the Modernizr.prefixed method will always return the JavaScript version of the style property. Modernizr.prefixed('transform') will return "WebkitTransform" in a Webkit browser. If you are using jQuery.css() this might not be a problem as jQuery.css() understands this format as well, if it's passed as the property (first parameter). However the prefixes might also be needed as the actual value of an style property. Consider the following:

 $('#myDiv').css(Modernizr.prefixed('transition'),Modernizr.prefixed('transform') + ' 1s linear');  

This snippet will attempt to set a transition on the "myDiv" HTML element using jQuerys´ "css" method and the Modernizr.prefixed method, but it will fail to do so. Why? Well, since jQuery is awesome it will allow us to pass "WebkitTransition" or "-webkit-transition" (if in a webkit browser) as the first parameter to the "css" method. For the second parameter jQuery.css() expects a CSS formatted string «-webkit-transform 1s linear», however the code above will generate «WebkitTransform 1s linear», which is not valid CSS and hence the entire method fails. What is needed is a Modernizr method which spits out a CSS formatted and prefixed string, let's call it "Modernizr.cssprefixed". Sadly this is not a part of Modernizr as of today, but the solution is given in the Modernizr.prefixed documentation, we only need a more convenient version of the RegExp given in the docs.

 Modernizr.cssprefixed = function(str)  
 {  
      return this.prefixed(str).replace(/([A-Z])/g,function(str,m1){   
         return '-' + m1.toLowerCase();   
      }).replace(/^ms-/,'-ms-');   
 }  

Now that we have this spanking new method we can update our line of code to:

 $('#myDiv').css(Modernizr.prefixed('transition'),Modernizr.cssprefixed('transform') + ' 1s linear');  

Voila, it works!

No comments: