Simple Calc() Support Test

A simple test for calc() support in the current browser. Based on modernizr code but not as verbose.

by Travis Almand

HTML

<p>This was my first version, didn't work in mobile.</p>
<pre>var calcSupport1 = !!$('&lt;div/>').css('width', 'calc(1px)').width();</pre>
<div id='result1'></div>

<p>Since it seems that this may not work with an element that hasn't been injected into the DOM, it always reported false. So, this is what I came up with instead.</p>
<pre>var calcSupport2 = !!$('head').css('width', 'calc(1px)').width();</pre>
<div id='result2'></div>

<p>You could just inject the div into the DOM so that it'll play nice with mobile. There will just an empty div in the body of the page.</p>
<pre>var calcSupport3 = !!$('&lt;div/>').appendTo('body').css('width', 'calc(1px)').width();</pre>
<div id='result3'></div>

<p>But I like the simplicity of using the head element since we won't care if it has size properties applied.</p>

JavaScript

var calcSupport1 = !!$('<div/>').css('width', 'calc(1px)').width();
var calcSupport2 = !!$('head').css('width', 'calc(1px)').width();
var calcSupport3 = !!$('<div/>').appendTo('body').css('width', 'calc(1px)').width();

$('#result1').text(calcSupport1);
$('#result2').text(calcSupport2);
$('#result3').text(calcSupport3);