0

I am trying to do the following math using JavaScript to edit the css. Here's the calculation I'm trying to do:

calc((100% / first) - (second * 2))

I'm not sure what the problem is, but it's not working. I tried taking away all the variables, and just have numbers (100%/3), and that worked.

Here's the JSFiddle, and here's the actual code:

$(document).ready(function() {
  var first = 3;
  var second = 10;

  $("p").css({
    // (100% / first) - (second * 2)
    "width": "calc((100%/" + first + ") - (" + second " * 2))"
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<h2>This is a heading</h2>

<p style="background-color:#ff0000">This is a paragraph.</p>
<p style="background-color:#00ff00">This is a paragraph.</p>
<p style="background-color:#0000ff">This is a paragraph.</p>
<p>This is a paragraph.</p>
Jessica
  • 9,379
  • 14
  • 65
  • 136
  • I hope you are aware of the support of [`calc`](http://caniuse.com/#search=calc) – Rayon Oct 22 '15 at 03:47
  • 1
    what is it supposed to do? I ran your jsfiddle with variables and with just numbers and both look the same. Also, if you're updating the css with javascript, why not just do the calculation in javascript? – Abdul Ahmad Oct 22 '15 at 03:51
  • 3
    The value used for `calc` is not valid, it has to be a simple expression, not multiple expressions with parenthesis. Also, there's a typo, missing a `+` – adeneo Oct 22 '15 at 03:55
  • So what do you suggest I do? – Jessica Oct 22 '15 at 17:15

1 Answers1

0

$(document).ready(function () {
    var first = 3;
    var second = 10;
    
    $("p").css({
  // (100% / first) - (second * 2)
        "width": "calc( 100% / " + first + " - " + second + " * 2px)"
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>This is a heading</h2>

    <p style="background-color:#ff0000">This is a paragraph.</p>
    <p style="background-color:#00ff00">This is a paragraph.</p>
    <p style="background-color:#0000ff">This is a paragraph.</p>
    <p>This is a paragraph.</p>
</body>
Mitul
  • 3,431
  • 2
  • 22
  • 35