Create a character counter in an input with JavaScript
Whether it's for choosing a username or for any other important data, you might need to limit the number of characters that your users can enter in a form field. Let's explore together in this article how to achieve this in a simple and effective way.
Step 1
The HTML code.
<label>
<input type="text" placeholder="Title" maxlength=20>
<span></span>
</label>
We only have a label enclosing an input tag and a span.
Step 2
It's now time to style the label and the input.
label {
position: relative;
}
input {
font-size: 1.4rem;
padding: .8rem 2rem .8rem 0;
background: transparent;
color: #F5F8FF;
border-bottom: 1.5px solid rgba(245, 248, 255, .4);
transition: all .4s;
outline: none;
}
We now proceed to style the label and the input.
label span {
position: absolute;
right: 0;
top: 50%;
transform: translateY(-50%);
width: 1.6rem;
height: 1.6rem;
display: flex;
align-items: center;
justify-content: center;
font-size: .8rem;
color: #F5F8FF;
background: rgba(245, 248, 255, .2);
border-radius: 5px;
}
In this step, we position our counter using absolute and perfectly center it thanks to the transform
property, which pushes the counter upwards by taking half of its size (50%).
Step 3
Let's style the input on focus and the placeholder.
input:focus {
border-color: #FF4754;
}
input::placeholder {
color: rgba(245, 248, 255, .4);
}
To ensure that we do not display a negative number of characters, we finish the function with a simple return.
Step 4
Let's style the counter (span
).
label span {
position: absolute;
right: 0;
top: 50%;
transform: translateY(-50%);
width: 1.6rem;
height: 1.6rem;
display: flex;
align-items: center;
justify-content: center;
font-size: .8rem;
color: #F5F8FF;
background: rgba(245, 248, 255, .2);
border-radius: 5px;
}
In this step, we use Flexbox (display: flex
) to horizontally and vertically center the number of characters to display.
Step 5
Finally, let's retrieve the necessary elements for our counter with JavaScript.
const input = document.querySelector('input');
const counter = document.querySelector('label span');
const maxLength = input.getAttribute('maxlength');
We retrieve the value of the maxlength
attribute to display it in the span tag.
Step 6
All that's left is to detect a change in the number of characters.
input.addEventListener('input', event => {
const valueLength = event.target.value.length;
const leftCharLength = maxLength - valueLength;
if (leftCharLength < 0) return;
counter.innerText = leftCharLength;
});
To ensure that we do not display a negative number of characters, we finish the function with a simple return.