2

I would like to calculate the width of 2 divs and pass the sum in a third, all values stocked in variables.

HTML:

<div id="value-a"></div>
<div id="value-b"></div>

<div id="value-c"></div>

JQuery:

var value_a = $('#value-a').css('width');
var value_b = $('#value-b').css('width');
var value_c = (value_a + value_b);
$('#value-c').css('width', value_c);

It look like i'm wrong with the syntax to make the operation...

Many thanks in advance for your help.

ketan
  • 19,129
  • 42
  • 60
  • 98
jjj
  • 965
  • 8
  • 23
  • You should also learn [__Debugging JavaScript__](https://developers.google.com/chrome-developer-tools/docs/javascript-debugging). Also see [What is a good Javascript debugging tool?](http://stackoverflow.com/questions/1739221/what-is-a-good-javascript-debugging-tool) – Satpal Apr 08 '14 at 06:21

3 Answers3

3

use .width():

var value_a = $('#value-a').width();
var value_b = $('#value-b').width();
var value_c = (value_a + value_b);
$('#value-c').width(value_c);
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
1

Try this Javascript Solution also

var value_a = document.getElementById("value-a").offsetWidth
var value_b = document.getElementById("value-b").offsetWidth
var value_c = (value_a + value_b);
document.getElementById("value-c").style.width=value_c+'px';
alert(value_c )

DEMO

Sridhar R
  • 20,190
  • 6
  • 38
  • 35
  • 1
    interesting solution, thanks, is it possible for example to calculate the "margin left" instead the "width" with this solution? – jjj Apr 08 '14 at 06:33
  • use `document.getElementById("value-a").style.marginLeft` – Sridhar R Apr 08 '14 at 06:40
1

One liner:

$('#value-c').width($('#value-a').width() + $('#value-b').width());
anar khalilov
  • 16,993
  • 9
  • 47
  • 62