Skip to content

Instantly share code, notes, and snippets.

@adamsilver
Created January 9, 2019 14:29
Show Gist options
  • Save adamsilver/93e0636648fd181412e33d8cf1a2e492 to your computer and use it in GitHub Desktop.
Save adamsilver/93e0636648fd181412e33d8cf1a2e492 to your computer and use it in GitHub Desktop.
Fix for rich text editor native contenteditable div etc
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