The fun project of the day is building a pincode that accepts pasting across multiple input fields. And we want to do all of this using just pure vanilla Javascript, no extra libraries.
So, the requirements are as follows:
- when manually typing it will automatically jump to the next input
- we can copy a code and paste it across multiple inputs, each digit from the code ending up in its corresponding input field
We will start with this basic HTML structure:
<form name="verify">
<div class="inputs">
<input type="text" name="n1" maxlength="1">
<input type="text" name="n2" maxlength="1">
<input type="text" name="n3" maxlength="1">
<input type="text" name="n4" maxlength="1">
</div>
</form>
You may have noticed that we are wrapping all in a form
element. This work great with using the input event. This event will get triggered each time a digit was inputted, thus allowing us to automatically move and focus the next input element:
const handleInput = ({target: input}) => {
if (input.nextElementSibling && input.value) {
input.nextElementSibling.focus()
}
}
form.addEventListener('input', handleInput);
The paste code handling is done by attaching a paste event listener to the inputs:
const handlePaste = (e) => {
const paste = e.clipboardData.getData('text')
inputs.forEach(
(input, i) => input.value = paste[i] || ''
)
}
inputs[0].addEventListener('paste', handlePaste);
The CSS is pretty simple. You can check it out in the full code of the example. The only thing to mention is the usage of the place-items to center elements in grids and using the :root selector to define the CSS variables.
You can see on GitHub pages the working example, and browse the full code of the example.
Posbile improvements to this example:
- limit the input types to just digits
- auto-select the first digit if we don't start from it
- triggering a Javascript event when the code has been fully entered
- trigger an exception when the pasted code is not the same length as the pin code component
And speaking of copy-paste events you may also want to check this tutorial about how to use the clipboard API in React and Javascript.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.