How do you implement auto-focus in an OTP input in JavaScript?
On the input event, if a value was entered and it is not the last input, focus the next input: if (value && index < inputs.length - 1) inputs[index + 1].focus(). This moves the cursor forward automatically.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in OTP Input Auto-Focus Implementation in JavaScript
On keydown, if the key is Backspace and the current input is empty (!e.target.value) and it is not the first input, focus the previous input: if (e.key === 'Backspace' && !e.target.value && index > 0) inputs[index - 1].focus().
Yes. Arrow Left and Arrow Right let the user navigate between inputs without typing. This improves UX for correction. On keyup, if ArrowLeft and index > 0, focus previous. If ArrowRight and not last, focus next.
Use CSS :focus and :focus-visible pseudo-classes. Change the border color and add a box-shadow: .otp-input:focus { border-color: #007bff; box-shadow: 0 0 0 3px rgba(0,123,255,0.2); }. This helps the user see which input is active.
Still have questions?
Browse all our FAQs or reach out to our support team
