<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.