Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery fallback function for CSS calc

I am trying to write a function in jQuery, which is designed to support browsers that do not support the CSS calc attribute.

I have the following so far:

function calc($element, $xy, $logic, $difference) {
    var calc = $($object).$xy() $logic $difference;
    return calc;
}

if ($.browser.msie && $.browser.version <= 8) {
    var height = calc("body", "height", "-", "80");
    $("div#page").css("height", height);
}

I can get away without having a function this one time, but for future reference, I think having this function would be really useful.

Obviously this line:

var calc = $($object).$xy() $logic $difference;

...is going to fail, but I don't know how to pass the variables into it properly.

If anybody has any advice on the syntax, or how I should be writing this line, that would be great.

like image 310
digiwig Avatar asked Apr 22 '26 10:04

digiwig


1 Answers

You could do something like this:

function calc( selector, method, adjust ) {
    return $(selector)[method]() + adjust;
}

if( $.browser.msie  &&  $.browser.version <= 8 ) {
    var height = calc( 'body', 'height', -80 );
    $('div#page').css( 'height', height );
}

A few notes on that code:

  • You don't need the $ prefix on your function parameters. If you're writing jQuery code, I recomment using a $ prefix only on variables that are references to jQuery objects, e.g.

    var $foo = $('#foo');  // cache jQuery object for later use
    
  • Note the square brackets used with [method] - that's how you can call a method whose name is stored in a variable.

  • I combined the math operation and value into a single adjust parameter. You could do something fancier, but it would be good to see more examples of how this code would be used first.

And a suggestion: if you are having to write JavaScript to do the sizing on browsers that don't support CSS calc, why not just use the JavaScript code in all browsers? Then you have only one code/style setup to debug instead of two.

like image 86
Michael Geary Avatar answered Apr 24 '26 22:04

Michael Geary