I want to have a input element for currency where there is a currency icon always at the center (but it adjusts according to the number of digits)
Something like:
This is what I've come up with:
const input = document.querySelector('input');
input.addEventListener('input', resizeInput);
resizeInput.call(input);
function resizeInput() {
this.style.width = this.value.length + "ch";
}
* {
font-size: 1.3em;
}
.currency_input {
width: 10em;
margin: 0;
position: absolute;
top: 50%;
left: 50%;
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
display: flex;
justify-content: center;
align-items: center;
border: 2px solid black;
border-radius: 15px;
}
input {
min-width: 10%;
max-width: 80%;
padding: 0.1em;
margin: 0.1em;
border: 0;
}
input:focus,
input:focus {
outline: none;
}
<div class="currency_input">
<span> $ </span>
<input type="text" name="name" autocomplete="off" maxlength="4">
</div>
Is there a better way? Things I haven't taken into considerations? Making it more responsive to be able to resize well? (Of course I will validate input later on)
width: 10em
, but then we switch from10em
toNNNch
?!? These are digits, so usingch
all the time seems appropriate. And if-ms-transform
is to support IE9 or something, we really need a comment explaining the impact and when we can delete such support. Amaxlength
of4
is maybe on the small side if people paste in comma / dot punctuation like1,000.00
or even$1,000.00
. Display what was entered, and worry about validating it later. \$\endgroup\$ch
I thought that it meant to have width of a character so I knew that I want the text input to grow by character size every time, and about the-ms-transform: translate(-50%, -50%);
, I copied it from somewhere else and I will remove 😅. How would you improve it? \$\endgroup\$em
(rather than e.g.px
) is Good. I think usingch
is Good. Both will adjust when user alters the font size. However, they express different things. So useem
consistently throughout. Or in this case, given that we're displaying digits, better to usech
throughout. Just don't switch fromem
toch
is all I was saying. (I anticipate that digits will all render with same width.) \$\endgroup\$