Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set equal width on divs with javascript

I've got five rows that looks like this: It's an ul with lis. I want the first li "text" to be equal on all rows. To do this I need to look for the widest li, then apply the new with to all li's.

(ul > li > span & ul)

Text > Li 1 | li 2 | Li 3
Textlong > Li 1 | li 2 | Li 3
Short > Li 1 | li 2 | Li 3
Longer13456 > Li 1 | li 2 | Li 3

I've used the following function for setting equal hights. Modified it a bit. But it does not make any sense!

function equalWidth() {
    var span = $('#tableLookAlike li.tr > span'),
        tallest = 0, 
        thisHeight = 0;

    setEqWidth = function(elem) {
        elem.each(function() {
            widest = 0;
            thisWidth = $(this).outerWidth();
            console.log(tallest, thisWidth)



// if I remove this it gives me the right width
                elem.each(function() {Width)
                    if (thisWidth > widest) {
                        widest = thisWidth;
                        elem.css({'width': widest});
                    }
                });
            });
        }

        setEqWidth(span);
    }

The log shows 92, 69, 68, 118 when I remove the second elem.each, and when I put it back, it gives me 92, 130, 168, 206. Does anyone know whats going on here?

Aynway, how do I solve this?

like image 932
patad Avatar asked Jun 04 '10 13:06

patad


3 Answers

If I was to do it, it would go something like this:

var greatestWidth = 0;   // Stores the greatest width

$(selector).each(function() {    // Select the elements you're comparing

    var theWidth = $(this).width();   // Grab the current width

    if( theWidth > greatestWidth) {   // If theWidth > the greatestWidth so far,
        greatestWidth = theWidth;     //    set greatestWidth to theWidth
    }
});

$(selector).width(greatestWidth);     // Update the elements you were comparing
like image 178
user113716 Avatar answered Sep 25 '22 01:09

user113716


A bit more concise

var widest = 0;
$("#tableLookAlike li.tr > span").each(function () { widest = Math.max(widest, $(this).outerWidth()); }).width(widest);
like image 29
Luc Avatar answered Sep 27 '22 01:09

Luc


You need to set the width of the elements at the end of your loop. Otherwise the widest value is just a temporary highest value.

setEqWidth = function(elem) {
    elem.each(function() {
        widest = 0;
        thisWidth = $(this).outerWidth();
        console.log(tallest, thisWidth)

        elem.each(function() {
                if (thisWidth > widest) {
                    widest = thisWidth;
                }
            });
        });


        elem.css({'width': widest});
    }
like image 29
HoLyVieR Avatar answered Sep 24 '22 01:09

HoLyVieR