Murphy1976
Murphy1976

Reputation: 1475

jQuery or Javascript to set all buttons to the width of the widest button

My client would like for me to write a sliver of code, jQuery preferred, that would set ALL the links to the same width of the widest link. Here's the HTML:

<div>
<h1>HEADER</h1>
<p style="text-align: right;" class="floatRight"><a href="#" class="small-button eLength"><span>BUTTON 1</span></a></p>
<p style="text-align: right;" class="floatRight"><a href="#" class="small-button eLength"><span>BUTTON 2</span></a></p>
<p style="text-align: right;" class="floatRight"><a href="#" class="small-button eLength"><span>BUTTON LONGEST</span></a></p>
</div>

The CSS sets all three buttons to a min-width of 180px. I'm looking for this all to hinge on the class: eLength

Upvotes: 2

Views: 655

Answers (2)

David Hellsing
David Hellsing

Reputation: 108500

You can get the max width like this:

var widest = Math.max.apply(Math, $('.eLength').map(function() { 
    return $(this).width(); 
}));

And to wrap this in a sliver plugin:

$.fn.widest = function() {
    return this.length ? this.width(Math.max.apply(Math, this.map(function() { 
        return $(this).width();
    }))) : this;
};

$('.eLength').widest();

Upvotes: 10

chridam
chridam

Reputation: 103395

Using John Resig's Fast JavaScript Max/Min:

Array.max = function(array) {
    return Math.max.apply(Math, array);
};

var widths = new Array();
$('.eLength').each(function(index) {
    widths.push($(this).width());
});

alert("Max Width: " + Array.max(widths));

Upvotes: 1

Related Questions