Jurģis Toms Liepiņš Jurģis Toms Liepiņš - 2 years ago 124
CSS Question

Restricting typing at a distance from the end on an input field

I have an input field, at the end of which i've created a character counter:

enter image description here

The problem is that now, it is possible to type beneath the counter which is no good:enter image description here

I would like the typing area to be restricted a certain distance before the end of the input field, something like this: enter image description here

I am aware of

but since the letters have different lengths i.e. you can fit 183 "i" but only 57 "W", which would make for a really unintuitive typing experience, if your typing is cut off at the middle of the field.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download