Last active
January 20, 2020 07:30
-
-
Save fourcolors/8c7dc745e5df882af023aa5cb2496a47 to your computer and use it in GitHub Desktop.
Svelte 9 Phone Field
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
const digits = Array(10).fill(null); | |
const focusNext = i => { | |
const next = digits[i + 1]; | |
if (Boolean(next)) next.focus(); | |
}; | |
const focusPrevious = i => { | |
const next = digits[i - 1]; | |
if (Boolean(next)) next.focus(); | |
}; | |
const isDigit = e => e.which >= 48 && e.which <= 57; | |
const deleteOrBackspace = e => e.which === 46 || e.which === 8; | |
const handleKeydown = e => { | |
if (!isDigit(e) && !deleteOrBackspace(e)) { | |
e.preventDefault(); | |
return; | |
} | |
}; | |
const handleKeyup = (e, i) => { | |
if (deleteOrBackspace(e)) { | |
focusPrevious(i); | |
} else if (isDigit) { | |
focusNext(i); | |
} | |
}; | |
</script> | |
<style> | |
.digit { | |
width: 20px; | |
height: 30px; | |
text-align: center; | |
font-size: 20px; | |
} | |
.phone-container { | |
font-size: 26px; | |
padding: 20px; | |
} | |
</style> | |
<div class="phone-container"> | |
+1 | |
{#each digits as d, i} | |
{#if i === 0}({/if} | |
{#if i === 3}){/if} | |
{#if i === 6}-{/if} | |
<input | |
on:keyup={e => handleKeyup(e, i)} | |
on:keydown={e => handleKeydown(e)} | |
bind:this={digits[i]} | |
class="digit" | |
type="tel" | |
maxlength="1" /> | |
{/each} | |
</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment