How can I check if CSS calc() is available using JavaScript?

Is there a way to check if the CSS function calc is available using JavaScript?

I found lot of questions and articles about getting the same behaviour as calc using jQuery, but how can I only check if it's available?

Answers:

Answer

In Modernizr you can find the test as css-calc currently in the non-core detects. They use the following code:

Modernizr.addTest('csscalc', function() {
    var prop = 'width:';
    var value = 'calc(10px);';
    var el = document.createElement('div');

    el.style.cssText = prop + Modernizr._prefixes.join(value + prop);

    return !!el.style.length;
});
Answer

A bit late to the party but I figured I should share this because I was myself struggling with it. Came up with the idea of by using jQuery, I can create a div that uses the calc() value in a CSS property (such as width in this case) and also a fallback width in case the browser does not support calc(). Now to check whether it supports it or not, this is what I did:

Let's create the CSS style for the currently "non-existing" div element.

/* CSS3 calc() fallback */
#css3-calc {
    width: 10px;
    width: calc(10px + 10px);
    display: none;
}

Now, if the browser does not support calc(), the element would return a width value of 10. If it does support it, it would return with 20. Doesn't matter what the values are exactly, but as long as the two width properties have different values in the end (in this case 10 and 20).

Now for the actual script. It's pretty simple and I suppose it's possible with regular JavaScript too, but here's the jQuery script:

// CSS3 calc() fallback (for unsupported browsers)
$('body').append('<div id="css3-calc"></div>');
if( $('#css3-calc').width() == 10) {
    // Put fallback code here!
}
$('#css3-calc').remove(); // Remove the test element

Alternatively, native javascript check, and width:

#css3-calc { width: 1px; width: calc(1px + 1px); }

if( document.getElementById('css3-calc').clientWidth==1 ){
    // clientHeight if you need height
    /* ... */
}
Answer

Calc detection was added to modernizer according to their news page. http://modernizr.com/news/

As well as tightening up support for existing tests, we've also added a number of new detects, many submitted by the community:

[...]
css-calc
Answer
var cssCheck = document.createElement("DIV");
cssCheck.style.marginLeft = "calc(1px)";
if (cssCheck.style.getPropertyValue("margin-left"))
{
    alert("calc is supported");
}
cssCheck = null;

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.