Use jQuery to Format Buttons Same Width

Use jQuery to Format Buttons Same Width

Some (many) user interfaces work best when buttons are sized identically, so that instead of this:

Buttons-DifferentSizes

or this:

Buttons-DifferentSizesVertical

You have something like this:

Buttons-SameSizes

This is pretty easy to do in JavaScript, and jQuery make it simple to apply the logic to a set of buttons with a common class. You can create a function, widest(), that, when applied to a set of buttons, sets its width to the widest button in the set. This is especially useful if you have a dynamic UI, perhaps because you’re localizing the text, for instance.

This is a somewhat tricky function to follow (for me at least). It starts out checking whether this.length is “truthy”, which will be true if it’s being applied to an array. If it’s not, then it just returns this (the “: this;” on the 4th line), doing nothing. Assuming an array is passed in, it will set the width property of each element to the result of a function. The function returns the max of the width of all elements in the array. So, if the elements started with widths of 25, 50, and 100, the function would return 100, and this would be set as the width for every element in the array.

This function can be applied to a group of buttons (perhaps all marked class=”buttons”) like this:

And this call can be made in the document ready function, or as part of a button click.

You can see a working example of this technique in this jsfiddle.

  • Oh no, please, don’t do it. Use css.

    • ardalis

      What’s the equivalent CSS (assuming you can’t just set it to its parent container’s width or otherwise cheat)?

        • ardalis

          Yeah, that’s probably the way to go, admittedly. The jQuery is interesting and “clever” but the CSS approach is certainly cleaner. The original requirement was for something horizontal, which is tougher than your quick example, but not by much, and the Bootstrap justified buttons would probably have done the trick (it was a while ago – this was in my blog backlog for a long time). Thanks for the feedback!