JSFiddle - React, Tailwind, and code Playground
by Terry Young
HTML
<h1>Duck-punching jQuery's .css() to workaround a CSS3 calc() issue</h1>
<p>Clicking the two buttons below should result in no difference in IE9+ and FF16+.</p>
<p>However, up to this writing, all webkit-based browsers still need the -webkit- prefix for the value.</p>
<p>That is, <code>$('div').css({ width: 'calc(100% - 200px)'});</code></p>
<p>versus, <code>$('div').css({ width: '-webkit-calc(100% - 200px)'});</code></p>
<p>Given such information <a href="http://caniuse.com/calc" target="_blank">[Can I use calc()]</a>, for those of you who intentionally need to use calc() as a CSS unit value, the following duck-punches jQuery's .css() method to apply the -webkit- prefix for you.</p>
<p>With the duck-punch applied, you can use the standardized implementation directly for all the mentioned browsers above.</p>
<hr>
<h2>Test</h2>
<div class="test">The width of this DIV should be (100% - 200px) in Webkit browsers (Safari/Google Chrome)</div>
<div class="buttons">
<button id="newCss">Apply new .css()</button>
<button id="oldCss">Revert to old .css()</button>
</div>
CSS
body {
background-color:#434343;
color:#fff;
}
body, button {
font-family:Arial;
font-size:12pt;
}
a {
color: #9999FF;
}
div {
padding: 10px;
}
div.test {
color:white;
background-color: #9c9c9c;
}
JavaScript
(function ($) {
var _oldCss = $.fn.css,
_newCss = function( name, value ) {
return $.access( this, function( elem, name, value ) {
var styles, len,
map = {},
i = 0;
if ( $.isArray( name ) ) {
styles = getStyles( elem );
len = name.length;
for ( ; i < len; i++ ) {
map[ name[ i ] ] = $.css( elem, name[ i ], false, styles );
}
return map;
}
return value !== undefined ?
$.trim(value).indexOf('calc')===0 ?
// Webkit detection script
// As there is no polyfill for CSS3 calc() specifically for webkit, this is a workaround on the issue
// @see http://stackoverflow.com/questions/6579901/how-to-test-for-mobile-webkit
// @see http://caniuse.com/calc
$.style (elem, name, (RegExp(" AppleWebKit/").test(navigator.userAgent) ? '-webkit-' : '')+value) :
$.style( elem, name, value ) :
$.css( elem, name );
}, name, value, arguments.length > 1 );
};
function runTest () {
$('div.test').css({
width: 'calc(100% - 200px)'
});
}
$('#newCss').on('click', function () {
$('div.test').css({width: 'inherit'}); // revert to inherit first
$.fn.css = _newCss;
runTest();
});
$('#oldCss').on('click', function () {
$('div.test').css({width: 'inherit'}); // revert to inherit first
$.fn.css = _oldCss;
runTest();
});
// initially run the test
$.fn.css = _newCss; // Duck-punch
runTest();
})(jQuery);