Cecil Theodore
Cecil Theodore

Reputation: 9939

Add to existing value using .each() JQuery

I have an .each() function that measures the width of each of the images within the class of .item. I need all the widths to be measured and then added to a variable. The variable then needs to be passed out of the function. This function below is only half done, I just dont know how to finish it off.

Any help much appreciated.

$('.item img').each(function () {

    var i = $(this).width();

});

$('.overview').css('width', i);

Upvotes: 2

Views: 5942

Answers (3)

Adil
Adil

Reputation: 148110

You were iterating through the items but the width is over written instead of adding up.

var i = $(this).width();

this would be

var i += $(this).width();

Also define I outside function to retain its value between function calls. The variable name i is not very appropriate here it could be something like totalImagesWidth

Try this

var i = 0;
$('.item img').each(function () {

    i += $(this).width();

});


$('.overview').css('width', i);

// you can pass this to some other function as well
somefunction(i);

Upvotes: 3

Razor
Razor

Reputation: 29588

var i = 0;

$('.item img').each(function () {
    i += $(this).width();
});

$('.overview').css('width', i);

Upvotes: 4

472084
472084

Reputation: 17885

var i = 0;

$('.item img').each(function () {

    i = i + $(this).width();

});

$('.overview').css('width', i);

Upvotes: 9

Related Questions