Interactive by Nature

Greatest element width with jQuery

I recently ran into a problem where I needed to get the greatest width of two dynamically loaded email addresses, and give that width to a custom “select” list, so that the select element was, at least, the same width as the widest child element.

Example:

custom select menu

Here’s the markup:

<input type="text" value="Select an email address" id="email" readonly="readonly">
<div id="dropdownOptions">
    <span class="custEmail"><a>email@address.com</a></span>
    <span class="custEmail"><a>really_long_email@address.com</a></span>
</div>

Here’s the JavaScript(jQuery):

var min_width = 160;

$('.custEmail').each(function(){
    var this_width = $('#dropdownOptions').outerWidth();
    if (this_width > min_width) {
        min_width = this_width;
    }
});

$('#email').css('min-width', min_width + 5 + 'px');

First, you’ll want to set a minimum width to the read only input field. I set it to 160 pixels minimum to compensate for the input value “Select an email address”. I want the user to be able to read the instructions. If a minimum width is not set, it will default to the width of the input value length because I have width:auto; in the CSS. It also gives the if statement nothing to compare to if not set.

Next, use the jQuery .each() function to run a child width check on all elements that use the class .custEmail. The variable “this_width” is set to get the full outer width of the email drop-down list with the id #dropdownOptions. Using outerWidth(); will return the width of the element, plus any padding and borders. The #dropdownOptions element will auto size to the width of the longest email address because it is the parent element to the two email addresses, thus giving us the width we want to pass to the read only input field. If the width of one of the email address is greater than 160 pixels, then the statement is true and “minimum_width” is now equal to “this_width”.

Lastly, we give the read only input field a new css min-width value. This value is whatever the new minimum_width value returns. I added 5 pixels to the width to compensate for the drop-down graphic in the read only input field.

Thats it! Happy Coding!

Leave a Comment