3

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.

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant! Thank you so much, again for the syntax advice this is really useful. Regarding your suggestion, yes this would seem a logical approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.