Skip to content

Instantly share code, notes, and snippets.

@litvinovvo
Last active July 29, 2024 18:55
Show Gist options
  • Save litvinovvo/f4473dddfffda379b33bb77103c5d27e to your computer and use it in GitHub Desktop.
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
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