Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<a href="javascript:void 0;">abc</a>
<div id="editor" contentEditable="true" style="white-space:pre;">
abc
</div>
<div id="editor2" contentEditable="true" style="white-space:pre;">
abc
</div>
def
<script>
let preventFlag = false;
function receiveKey(event){
if(event.keyCode === "\r".charCodeAt(0) && !event.shiftKey) {
let range = document.getSelection().getRangeAt(0);
range.deleteContents();
range.insertNode(document.createTextNode("\n"));
//TODO:
range.setStart(range.endContainer, range.endOffset);
this.normalize();
event.preventDefault();
}
//TODO: tab
}
function receiveChange(event){
// var staticRange = event.getTargetRanges()[0];
let staticRange = event.getTargetRanges()[0];
let s = event.dataTransfer && event.dataTransfer.getData("text/plain");
if(event.inputType === "insertParagraph") {
throw new Exception("This should never happen.");
}
if(event.inputType === "deleteByDrag"
|| event.inputType === "deleteByCut"
|| event.inputType === "deleteContentBackward"
|| event.inputType === "deleteContentForward"
|| event.inputType === "deleteWordBackward"
|| event.inputType === "deleteWordForward") {
//TODO:
console.log(event.data)
}
if(event.inputType.match(/^format/)) {
event.preventDefault();
}
if(event.inputType === "insertText") {
//TODO:
}
if(event.inputType === "insertReplacementText") {
//TODO:
}
if(event.inputType === "insertLineBreak") {
//TODO:
}
if(event.inputType === "historyRedo" || event.inputType === "historyUndo") {
//TODO:
}
if(event.inputType === "insertFromPaste" || event.inputType === "insertFromDrop" ) {
let range = document.createRange();
range.setStart(staticRange.startContainer, staticRange.startOffset);
range.setEnd(staticRange.endContainer, staticRange.endOffset);
let s = event.dataTransfer.getData("text/plain");
range.deleteContents();
range.insertNode(document.createTextNode(s));
//TODO:
let selection = window.getSelection();
range.setStart(range.endContainer, range.endOffset);
selection.removeAllRanges();
selection.addRange(range);
this.normalize();
event.preventDefault();
}
console.log(staticRange, s, event.data);
}
function press(event){
console.log("press")
}
document.querySelector("#editor").addEventListener("keypress", receiveKey);
document.querySelector("#editor").addEventListener("beforeinput", receiveChange);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment