Reputation: 1520
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
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
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
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
Reputation: 30975
One way in a lot :
$sum = 0;
$('.navigation-bar .nav li').each(function(){
$sum = $sum + $(this).width();
});
alert($sum);
Upvotes: 3