Mike Vierwind
Mike Vierwind

Reputation: 1520

Get the combined width of all li items

I made a function to get all the widths of all the li items in the navigation menu, but this function (below) puts all the item's widths into an array.

I do not need not an array. I just need one total number that is the sum of all the li's widths.

How can I change the array to one variable?

Thank you.

var navigationItemsWidth = $.map($('.navigation-bar .nav li'),function(val){
    return $(val).width();
});

Upvotes: 0

Views: 111

Answers (4)

row1
row1

Reputation: 5578

var navigationItemsWidth = (function(){
  var total = 0;
  $('.navigation-bar .nav li').each(function() { total+=$(this).width();});
  return total;
})();

Or if you want to reuse that function you can extract it out rather than executing it straight away, or add it as a jQuery plugin

$.fn.totalWidth = function() {
 var total = 0;
 this.each(function() { total+=$(this).width();});
  return total;
};

var navigationItemsWidth = $('.navigation-bar .nav li').totalWidth();

Upvotes: 2

Karl-André Gagnon
Karl-André Gagnon

Reputation: 33870

Map is a function that create an array, what you want is adding a value. use .each:

var navigationItemsWidth = 0;
$('.navigation-bar .nav li').each(function(){
    navigationItemsWidth += $(this).width();
});

If you want to reuse it, use this :

$.fn.totalWidth = function(){
    var navigationItemsWidth = 0;
    this.each(function(){
        navigationItemsWidth += $(this).width();
    });    
    return navigationItemsWidth;
}

var navigationItemsWidth = $('navigation-bar .nav li').totalWidth()

Upvotes: 4

user2718671
user2718671

Reputation: 2976

This should work:

var count = $('.navigation-bar .nav li').size();
var list_items_width=array();
for (var i = 0; i < count; i++) {
     list_items_width.push($('.navigation-bar .nav li').eq(i).width());
}
var total_width = 0;
for (var j = 0; j < count; j++) {
    total_width = total_width + list_items_width[j];
}

Upvotes: -1

BENARD Patrick
BENARD Patrick

Reputation: 30975

One way in a lot :

$sum = 0;

$('.navigation-bar .nav li').each(function(){
   $sum = $sum + $(this).width();
});

alert($sum);

Upvotes: 3

Related Questions