9

I have made a quick Jsbin: http://jsbin.com/ujabew/edit#javascript,html,live

What i'm trying to achieve is to find out which is the largest <section> out of the 3 from the link. So what i'd like is to, after the loop runs, is to have var width set to the largest possible number that any of the widths could be.

Code in progress posted in link

benhowdle89
  • 36,900
  • 69
  • 202
  • 331

7 Answers7

33

Here:

var maxWidth = Math.max.apply( null, $( elems ).map( function () {
    return $( this ).outerWidth( true );
}).get() );

Live demo: http://jsfiddle.net/rM4UG/

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
  • Nice one. When I used this, it was for elements just inside the body that had margin: auto (for centering purposes). If you're doing something similar in IE (standards mode), remove the true being passed into the `outerWidth` function to remove margins from the calculation and you're golden! – Greg Pettit Jan 24 '12 at 16:15
3

Fleshing out Marc B's comment, using Math.max():

$(document).ready(function(){
  var maxWidth = 0;
  $('.content ul li').each(function(){
    var itemWidth = $(this).outerWidth(true);
    maxWidth = Math.max(maxWidth, itemWidth)
  });
});
Carl Raymond
  • 4,429
  • 2
  • 25
  • 39
0

I have just written a function regarding this. I thought it might help others. (jQuery)

$.fn.largerWidth = function () {    //function(p)  
                                    // where 'p' can be clientWidth or offsetWidth 
                                    // or anything else related to width or height
    var s = this,m;
    for (var i = 0; i < s.length; i++) {
        var w = s[i].offsetWidth;   // s[i][p]; 
        (!m || w > m) ? (m = w) : null
    }
    return m;
}
Mr_Green
  • 40,727
  • 45
  • 159
  • 271
0

I believe you want to look into the underscore library. Specifically, the max method

Zee Spencer
  • 3,460
  • 6
  • 29
  • 31
0
$(document).ready(function(){
  var maxWidth = 0;
  $('section').each(function(){
    w = $(this).outerWidth(true);      
    if ( w > maxWidth)
            maxWidth = w;
  });
});
kaz
  • 1,943
  • 1
  • 13
  • 19
0

Change the .each() loop to this:

var thisWidth = $(this).outerWidth(true);

if (thisWidth > width) {
    width = thisWidth;
}
powerbuoy
  • 12,460
  • 7
  • 48
  • 78
0

This was my idea:

$(document).ready(function () {
  var elements = $(".content ul li");
  var count = elements.length - 1;
  var width = [];

  elements.each(function (n) {
    width.push($(this).outerWidth(true));
    if (count == n) {
      width = Math.max.apply(Math, width);
    }
  });
});

I added the count of the number of elements and then runs the Math.max to get the largest number when each loop is done.

Einar Ólafsson
  • 3,036
  • 1
  • 19
  • 24