2

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);

3 Answers 3

9
var i = 0;

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

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

});

$('.overview').css('width', i);
Sign up to request clarification or add additional context in comments.

Comments

4
var i = 0;

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

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

Comments

3

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);

2 Comments

Good answer based on the question, the original asker might want to consider changing the name of the i var to something more descriptive.
Yes very true, i for variable name is not suited here. I mentioned in my answer to change i to more appropriate name.

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.