Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question

1 Answer

up vote 1 down vote accepted

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.

share|improve this answer
Brilliant! Thank you so much, again for the syntax advice this is really useful. Regarding your suggestion, yes this would seem a logical approach. – digiwig Mar 26 at 9:14

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.