(WIP) Maskr Demo

https://github.com/lukeed/maskr

by Luke Edwards

HTML

<form id="form">
  <label>Empty Input</label>
	<input data-mask="(___) ___-____" />
	<label>Valued Input</label>
  <input value="123" data-mask="_-_-_" />
	<label>Partially-Valued Input</label>
	<input value="W" data-mask="Hello, _____!" />
</form>

CSS

input,label {
	display: block;
}
label {
	margin-top: 8px;
}

JavaScript

const form = document.getElementById('form');
const inputs = form.querySelectorAll('input');

function setValue(ev) {
  if (ev !== void 0 && ev.type === 'keydown') {
    ev.preventDefault();
    this._value += ev.key;
  }
  const mask = this.getAttribute('data-mask');
  const out = maskr(mask, this._value);
  // set visible value
  this.value = out.value;
  // set cursor position
  this.setSelectionRange(out.cursor, out.cursor);
}

[].forEach.call(inputs, el => {
  if (!el.hasAttribute('data-mask')) return;
  // init internal tracking
  el._value = el.value || '';
	// first-run if has value
	(el.value.length > 0) && setValue.call(el);
  // attach listeners
  el.onfocus = el.onkeydown = setValue.bind(el);
});


function maskr (mask, input) {
	var val='', idx=0, pos=0, i=0;
	for (; i < mask.length; i++) {
		if (mask[i] === '_') {
			if (input[idx] !== void 0) {
				val += input[idx];
				idx += 1; // move 1
			} else {
				pos = pos || i;
				val += '_';
			}
		} else {
			val += mask[i];
		}
	}
	return { value:val, cursor:pos };
}