1

I have a bit of jQuery to get the size of a ul container, and automatically set the padding on each li to fill the space accordingly as each li is a different size. i have these variables set up to get the width of each li, but i can't work out how to get the total width of each li added together.

$('nav ul li').each(function() {
    var $this = $(this),
        width = $this.outerWidth();

    $this.after($('<div>' + width + '</div>'));
});

The div after is just a test to check its getting the correct width. How do i add up the total width of each li? Thanks!

Tim Wilkinson
  • 3,761
  • 11
  • 34
  • 62

2 Answers2

2

Just define your width variable outside the each function and update it each time it is called:

var width = 0;
$('nav ul li').each(function() {
    var $this = $(this);
    width += $this.outerWidth();

    $this.after($('<div>' + width + '</div>'));
});

FYI, this works because of javascript closures. Take a look at this question for an explanation: How do JavaScript closures work?

Community
  • 1
  • 1
cfs
  • 10,610
  • 3
  • 30
  • 43
  • sorry? thanks for the response, but im not sure i understand how will defining the width variable outside the each function return the total sum of all list item widths? – Tim Wilkinson Jun 07 '13 at 12:58
  • 1
    `width` starts as 0, and in each iteration of the `each` function, the outer width of the next element will be added to `width` (notice the `+=`). After 'each' has iterated through all the elements, `width` will be the sum of all outer widths. – cfs Jun 07 '13 at 13:08
  • 1
    thank you, im so sorry i completely missed the += and as a result couldnt work out your responce. Thats spot on thank you!! – Tim Wilkinson Jun 07 '13 at 13:20
1

In your case with is local variable.So the width will not update

var width  = 0;

$('nav ul li').each(function() {
    var $this = $(this),
        width =width + $this.outerWidth();
       $this.after($('<div>' + width + '</div>'));   

});
PSR
  • 39,804
  • 41
  • 111
  • 151