Skip to content

Instantly share code, notes, and snippets.

@unrevised6419
Last active July 17, 2018 10:59
Show Gist options
  • Save unrevised6419/cbed33e89a1e1a0cdd81ad0df041879a to your computer and use it in GitHub Desktop.
Save unrevised6419/cbed33e89a1e1a0cdd81ad0df041879a to your computer and use it in GitHub Desktop.
Map input chars to another chars
<input type="text">
const input = document.querySelector('input')
// this is the order of events into an input
input.addEventListener('focus', onFocus)
input.addEventListener('keydown', keyDown)
input.addEventListener('keypress', keyPress)
input.addEventListener('input', onInput)
input.addEventListener('keyup', keyUp)
input.addEventListener('change', onChange)
input.addEventListener('blur', onBlur)
function onFocus (event) { info(event) }
function keyDown (event) { info(event) }
function keyPress (event) {
info(event)
// this 2 calls will stop `input` and `change` events
event.preventDefault();
event.stopPropagation();
// get current props
const target = event.target
const start = target.selectionStart;
const end = target.selectionEnd;
const val = target.value;
// get some char based on event
const char = getChar(event);
// create new value
const value = val.slice(0, start) + char + val.slice(end);
// first attemp to set value
// (doesn't work in react because value setter is overrided)
// target.value = value
// second attemp to set value, get native setter
const nativeInputValueSetter = Object.getOwnPropertyDescriptor(
window.HTMLInputElement.prototype,
"value"
).set;
nativeInputValueSetter.call(target, value);
// change cursor position
target.selectionStart = target.selectionEnd = start + 1;
// dispatch `input` again
const newEvent = new InputEvent('input', {
bubbles: true,
inputType: 'insertText',
data: char
})
event.target.dispatchEvent(newEvent);
}
function keyUp (event) { info(event) }
function onInput (event) { info(event) }
function onChange (event) { info(event) }
function onBlur (event) {
// dispatch `change` again
const newEvent = new Event('change', { bubbles: true })
event.target.dispatchEvent(newEvent);
info(event)
}
function info (event) { console.log(event.type) }
function getChar(event) {
// will show X if letter, will show Y if Digit, otherwise Z
return event.code.startsWith('Key')
? 'X'
: event.code.startsWith('Digit')
? 'Y'
: 'Z'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment