A simple component for number-only segmented input. Ideal for 2FA codes. Minified and gzipped the package is ~9kb, and can be used with svelte's client-side component API in non-svelte projects.
NOTE: Deprecated
<script>
import SvelteSegmentedInput from 'svelte-segmented-input'
let value
let callback = (e) => console.log(e)
</script>
<SvelteSegmentedInput bind:value="{value}" length="{6}" style="{{borderColor: 'black', inputWidth: '50%'}}" on:valueEntered="{callback}" />
value
is the current value of the input as a string with spaces in non-populated fields. Setting rhe variable value will change the input value to the given input if it's a number or can be coerced to a number.
length
is the number of fields. accepts number or an array of numbers. when an array is passed, it will create the segments such as for an array [3, 3, 4] the input will look like this: [] [] [] - [] [] [] - [] [] [] [].
style
is an object which holds sets custom CSS properties to control the styling of the component.
on:valueEntered
is an event that fires every time a full value is entered. event.detail.value
is the value that was entered.
import SegmentedInput from 'svelte-segmented-input'
const component = new SegmentedInput({
target: document.querySelector('#app'), // where to attach the component in the DOM
props: {
length: 6, // length of the input; can be an array to specify segments
value: 123, // initial value
},
})
// event listener. removeEvent() will remove the event listener
const removeEvent = component.$on('valueEntered', (e) => console.log(e.detail.value))
// log the current value of the component
console.log(component.value)
Setting value in the props object will not trigger the valueEntered
event, however setting it using component.value
will
justify content: space-between;
insteadAlternatively, you can target each item with a descendant selector, as all elements are inside a div with id #input-wrapper.
length
property will break when length is smaller than the number of fields that are populated. Please, don't bind the length
property.