I´ve been trying to make the ratio between two input values to be locked if a checkbox is checked.
I´ve come with the code below which looks like it works, yet it has some strange behavior. Most of the time it works fine yet sometimes it throws some random result or more often wouldn't work with the first onchange event yet logging the results.
const
widthInput = document.getElementById('width'),
heightInput = document.getElementById('height'),
ratioLock = document.getElementById('ratioLock');
let
lastWidthValue = +widthInput.value,
lastHeightValue = +heightInput.value;
widthInput.onchange = () => {
if (ratioLock.checked) {
if (lastWidthValue === 0) {
lastWidthValue = +widthInput.value;
lastHeightValue = +heightInput.value;
}
let ratio = +widthInput.value / lastWidthValue;
heightInput.value = +(ratio * +heightInput.value);
lastWidthValue = +widthInput.value;
lastHeightValue = +heightInput.value;
console.log(lastHeightValue, lastWidthValue)
}
};
heightInput.onchange = () => {
if (ratioLock.checked) {
if (lastHeightValue === 0) {
lastHeightValue = +heightInput.value;
lastWidthValue = +widthInput.value;
}
let ratio = +heightInput.value / lastHeightValue;
widthInput.value = +(ratio * +widthInput.value);
lastHeightValue = +heightInput.value;
lastWidthValue = +widthInput.value;
console.log(lastHeightValue, lastWidthValue)
}
};
ratioLock.onchange = () => {
lastWidthValue = +widthInput.value;
lastHeightValue = +heightInput.value;
console.log(lastHeightValue, lastWidthValue)
};
<body>
<label for="width"> Size: </label><br />
<input id="width" inputmode="numeric" type="number" placeholder="Width"> x
<input id="height" inputmode="numeric" type="number" placeholder="Height"> pixels. <br />
<input id="ratioLock" type="checkbox">
<label for="ratioLock"> Lock aspect ratio. </label><br />
</body>
Something I found interesting is that when I isolated that piece of code (I mean removing it from the rest of code I'm writing with all the other inputs, styles and other functions) and tested it by itself it worked pretty fine and didn't find any strange behavior so I don't know if it has to do with something else than the code itself. Also I think maybe there is another, shorter 'more elegant' way of achieving this.