I have an input field, at the end of which i've created a character counter:
The problem is that now, it is possible to type beneath the counter which is no good:
I would like the typing area to be restricted a certain distance before the end of the input field, something like this:
I am aware of
The two possible solutions that occur to me.
Simply shortening the input and positioning the counter next to the input, then styling a common parent element to look like the input. This is the more simple and less error prone solution.
This way is a bit more complicated, but basically what you would do is create a hidden element somewhere (NB not
display: none;) with the same font size/weight/family and attach a
keydown event handler to the input field.
In this handler you copy the contents on the input to the hidden element, measure the width in pixels and compare that to your input. If the difference is too small, you return false in your input handler, making sure you're not preventing the user from pressing delete or backspace first.
It should be noted however that this method is pretty difficult to get right and I would consider it to be the "dirty" solution.