Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Javascript to size 2 buttons based on which contains the longest content

Scenario:

  1. User enters text "thisisabutton" for ButtonA

  2. User enters text "thisisalongerbutton" for ButtonB

  3. Both buttons dynamically adapt in size to fit text length, thus making them 2 different sizes

  4. I want ButtonA to be the same size as ButtonB (which will determine the size since it's longer than ButtonA).

What is the best approach to do this in Javascript?

like image 266
user1876989 Avatar asked Dec 06 '25 06:12

user1876989


1 Answers

<button id="ButtonA" onChange="ResizeButtons();">Hello</button>
<button id="ButtonB" onChange="ResizeButtons();">Worlddddddddddddddd</button>
<script type="text/javascript">
    function getWidth(element) {
        return parseInt(window.getComputedStyle ? window.getComputedStyle(element,null).getPropertyValue("width")  : element.currentStyle.width );
    }
    function ResizeButtons() {
        var buttonA = document.getElementById("ButtonA");
        var buttonB = document.getElementById("ButtonB");
        buttonA.style.width = "auto";
        buttonB.style.width = "auto";
        var buttonAWidth = getWidth(buttonA);
        var buttonBWidth = getWidth(buttonB);
        var maxWidth = (buttonAWidth > buttonBWidth ? buttonAWidth: buttonBWidth) + "px";
        buttonA.style.width = maxWidth;
        buttonB.style.width = maxWidth;
    }
</script>

1) Cross Browser.

2) Resets elements to "auto" before computing, or else they'll never resize after the first character is entered.

3) Avoids re-accessing DOM after getting buttonA and buttonB.

4) Checks while each button is being modified.

EDIT

You may have to put the ResizeButtons(); event on the inputs you're using to change the button content, or better yet, simply run the function ResizeButtons() inside your current script that changes the button content, immediately after the content is changed.

like image 135
Randy Hall Avatar answered Dec 07 '25 20:12

Randy Hall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!