David Van Staden
David Van Staden

Reputation: 1779

Calculating heights and adding to a variable

Good Day

I have the following function that calculates the height of each div and adds it to a variable, but it is not working:

JS:

$('#latestInner, #make, #models').each(function() {
    var i = 0;
    var h = $(this).outerHeight();
    i = i + h;
});
alert(i);

HTML:

<div id="latestInner"></div>
<div id="make"></div>
<div id="models"></div>

CSS:

#models {height: 100px; background: red;}
#latestInner {height: 200px; background: green;}
#make {height: 150px; background: blue;}

FIDDLE: http://jsfiddle.net/uwsJH/7/

Upvotes: 0

Views: 48

Answers (4)

Tschallacka
Tschallacka

Reputation: 28742

Your problem was scoping.

Try this fiddle:

http://jsfiddle.net/uwsJH/9/

i=0;
$('#latestInner, #make, #models').each(function() {
   // var i = 0; <--- wrong scope
    var h = $(this).outerHeight();
    i = i + h;
});
alert(i);

Upvotes: 2

Gurmeet
Gurmeet

Reputation: 3314

try this :

var i = 0;
$('#latestInner, #make, #models').each(function() {

var h = $(this).css("height");
i = i + h;
});

Upvotes: 1

JoDev
JoDev

Reputation: 6873

You don't need to initialize the var i at each time... You can do it this way :

var i = 0;
$('#latestInner, #make, #models').each(function() {

    var h = $(this).outerHeight();
    i = i + h;
    //Or simply
    i = i + $(this).outerHeight();
});
alert(i);

Upvotes: 0

vborutenko
vborutenko

Reputation: 4443

Because i is a local variable.Try i = 0 ,instead var i =0

Upvotes: 1

Related Questions