Created
January 9, 2019 14:29
-
-
Save adamsilver/93e0636648fd181412e33d8cf1a2e492 to your computer and use it in GitHub Desktop.
Fix for rich text editor native contenteditable div etc
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
onKeyUp(event) { | |
const div = this.textarea.nativeElement; | |
const firstChild = div.firstChild; | |
const lastChild = div.lastChild; | |
if ( | |
event.keyCode === 13 | |
&& !event.shiftKey | |
&& firstChild.nodeName.toLowerCase() !== 'p' | |
) { | |
const content = div.innerHTML; | |
const firstPIndex = content.indexOf('<p>'); // there always be a <p> because of keyCode 13 | |
while(div.hasChildNodes()){ // remove all because b or u tags etc will not be in first child | |
div.removeChild(div.lastChild); | |
} | |
const p: HTMLParagraphElement = document.createElement('p'); | |
p.innerHTML = content.slice(0, firstPIndex); | |
div.insertBefore(lastChild, div.firstChild); | |
div.insertBefore(p, div.firstChild); | |
const selection = window.getSelection(); | |
selection.collapse(div.lastChild, div.lastChild.length); // set cursor to end | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment