Skip to content

Instantly share code, notes, and snippets.

@kilgarenone
Last active November 1, 2019 04:39
Show Gist options
  • Save kilgarenone/bd9d17f439193e1d812048d359c74a09 to your computer and use it in GitHub Desktop.
Save kilgarenone/bd9d17f439193e1d812048d359c74a09 to your computer and use it in GitHub Desktop.
import { h, Component } from "preact";
class Otp extends Component {
// onKeyDown event is triggered BEFORE onKeyPress event
keyDown = e => {
const { keyCode } = e;
const wasNonNumericEntered = !(keyCode >= 48 && keyCode <= 57) && !(keyCode >= 96 && keyCode <= 105);
// don't do anything if entered non-numeric values
if (wasNonNumericEntered) e.preventDefault();
// if backspace or del were pressed...
if (keyCode === 8 || keyCode === 46) {
// clear the current focused input's value
e.target.value = "";
// then clear its left-side adjacent input's value
e.target.previousElementSibling.value = "";
// then focus the left-side adjacent input
e.target.previousElementSibling && e.target.previousElementSibling.focus();
}
// if current input ele already has value, clear it on keydown event first,
// so that subsequent keypress event will replace it with a value
if (!wasNonNumericEntered && e.target.value) e.target.value = "";
};
keyUp = async e => {
// if non-numeric values were entered, don't focus right-side adjacent input ele
if (
!(e.keyCode >= 48 && e.keyCode <= 57) &&
!(e.keyCode >= 96 && e.keyCode <= 105)
)
return;
// if numeric value was entered, then focus the right-side adjacent input ele
e.target.nextElementSibling && e.target.nextElementSibling.focus();
};
render() {
return (
<div class="otp" onKeyDown={this.keyDown} onKeyUp={this.keyUp}>
<input autoFocus type="tel" />
<input type="tel" />
<input type="tel" />
<input type="tel" />
<input type="tel" />
<input type="tel" />
</div>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment