HTML
<aside>
<input type="text" placeholder="_" maxlength="0" autofocus />
<input type="text" placeholder="_" maxlength="0" />
<input type="text" placeholder="_" maxlength="0" />
<input type="text" placeholder="_" maxlength="0" />
<input type="text" placeholder="_" maxlength="0" />
<input type="text" placeholder="_" maxlength="0" />
</aside>
<!-- Also you can mask the entered value, with type 'password'. -->
CSS
aside {
display: flex;
justify-content: center;
flex-wrap: wrap;
gap: 0.6rem;
input {
width: 1.1rem;
padding: 0.4rem 0.7rem;
border-radius: 0.2rem 0.2rem 0 0;
border: none;
border-bottom: solid 0.2rem #883aea;
text-align: center;
font-size: 1.2rem;
font-weight: bold;
background-color: transparent;
color: #fff;
caret-color: #883aea;
transition: transform 0.2s, border-bottom-color 0.2s, background-color 0.5s;
cursor: default;
&:focus {
outline: none;
border-bottom-color: #e0ccfa;
animation: border-bottom-pulse 1s infinite 1.5s;
}
&::placeholder {
color: #e0ccfa;
opacity: 0.8;
}
&:focus::placeholder {
opacity: 0;
}
&:hover {
transform: translateY(-3px);
background-color: #310a65;
}
}
}
@keyframes border-bottom-pulse {
50% {
border-bottom-color: #883aea;
}
}
Javascript
const element = document.querySelector("aside");
const regex = /^[a-zA-Z0-9]$/; //Customize the allowed input values
element.addEventListener("keydown", (e) => {
if (e.ctrlKey || e.altKey) return;
if (
regex.test(e.key) ||
e.code === "Backspace" ||
e.code === "Delete" ||
e.code === "ArrowLeft" ||
e.code === "ArrowRight"
) {
if (!(e.code === "ArrowLeft" || e.code === "ArrowRight")) {
e.target.value =
e.code === "Backspace" || e.code === "Delete" ? "" : e.key;
}
e.code === "Backspace" || e.code === "ArrowLeft"
? e.target.previousElementSibling?.focus()
: e.target.nextElementSibling?.focus();
}
});
element.addEventListener("paste", (e) => {
const parent = e.target.parentElement;
const code = e.clipboardData
?.getData("text")
.split("", parent.childElementCount);
let child = parent.firstElementChild;
code.forEach((char) => {
child.value = regex.test(char) ? char : "";
child = child.nextElementSibling;
child?.focus();
});
});