Last active
July 29, 2024 18:55
-
-
Save litvinovvo/f4473dddfffda379b33bb77103c5d27e to your computer and use it in GitHub Desktop.
contenteditable div with textarea like behaviour for plain text, correct process new lines on enter
This file contains hidden or 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
function onKeypress(event: KeyboardEvent) { | |
const isEnter = ['Enter', '\n'].includes(event.key) | |
if (isEnter && !event.shiftKey) { | |
// document.execCommand('insertLineBreak') // short and more solid alternative, despide of deprecation | |
const selection = window.getSelection() | |
if (selection) { | |
const range = selection.getRangeAt(0) | |
const br = document.createElement('br') | |
const editableDiv = event.target as HTMLDivElement | |
if (!editableDiv.innerText?.endsWith('\n')) { | |
editableDiv.appendChild(document.createElement('br')) | |
} | |
range.insertNode(br) | |
range.setStartAfter(br) | |
range.setEndAfter(br) | |
selection.removeAllRanges() | |
selection.addRange(range) | |
const inputEvent = new Event('input', { | |
bubbles: true, | |
cancelable: true, | |
}) | |
event.target?.dispatchEvent(inputEvent) | |
} | |
event.preventDefault() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment