Created
February 21, 2017 16:57
-
-
Save ggkrustev/ee69f9d0e1a3d74f84f08593aa56d57c to your computer and use it in GitHub Desktop.
Detect changes in the input event listening only to the `input` event
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title>Input - detect changes in the text</title> | |
</head> | |
<body> | |
<input id="dateinput" /> | |
<script> | |
const startMatchIndex = (origin = "", candidate = "") => { | |
const length = origin.length; | |
let idx = 0; | |
while (origin[idx] === candidate[idx] && idx < length) { | |
idx += 1; | |
} | |
return idx; | |
}; | |
const endMatchIndex = (origin = "", candidate = "") => { | |
let originIdx = origin.length - 1; | |
let candidateIdx = candidate.length - 1; | |
let idx = 0; | |
while (origin[originIdx] === candidate[candidateIdx]) { | |
candidateIdx -= 1; | |
originIdx -= 1; | |
idx += 1; | |
} | |
return idx; | |
}; | |
const lastIndex = (value, end) => value.length - end; | |
const info = (value, start, end) => ({ | |
start: value.substring(0, start), | |
end: value.substring(end, value.length), | |
changed: value.substring(start, end) | |
}); | |
const stateChecker = (oldInfo, newInfo) => { | |
if (!oldInfo.changed && !newInfo.changed) { | |
console.log("no changes"); | |
} | |
if (oldInfo.changed && !newInfo.changed) { | |
console.log("deletion"); | |
} | |
if (!oldInfo.changed && newInfo.changed) { | |
console.log("typing"); | |
} | |
if (oldInfo.changed && newInfo.changed) { | |
console.log("replace text"); | |
} | |
}; | |
window.addEventListener("DOMContentLoaded", () => { | |
const input = document.getElementById('dateinput'); | |
let oldValue = ""; | |
input.addEventListener("input", ({ target }) => { | |
const startIdx = startMatchIndex(oldValue, target.value); | |
const endIdx = endMatchIndex(oldValue, target.value); | |
const newValue = target.value; | |
const oldInfo = info(oldValue, startIdx, lastIndex(oldValue, endIdx)); | |
const newInfo = info(newValue, startIdx, lastIndex(newValue, endIdx)); | |
oldValue = target.value; | |
stateChecker(oldInfo, newInfo); | |
}); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment