When you are on discord you can highlight text only using the keyboard like this: **this would be bold text**
.
I want to create a similar system in a browser-based text-editor, entirely coded by me, while also adding my own twists, like colors, and comments, like what you would see inside vsc. So it would look like this:
#bold text# /yyellow text/y
What I've came up with:
- made the div
contenteditable
- at every keystroke, I took the text into a variable, and basically just used the
.replace()
function, putting<span class="...">text</span>
everywhere needed. And then just moving the text back onto the page all at once usingdocument.getElementById().innerHTML
.
The problem was, that when i reset the div, the caret would return back to the start of the div.
So I found Restore cursor position after changing contenteditable on stackoverflow. But it didnt work when I had more than one spans in each other like:
<span class="bold"><span class="yellow">text</span></span>
And my last try was using document.execCommand(), but it doesn't work, because you have to highlight the text before.
And because I cant find any more code I could use, I'm asking for help.
UPDATE: Kelly's answer did fix my original issue, but created a new one. I can't input new lines.
I can't press enter, because .innerText
doesnt recognize that.
br, and div break the caret-fix.
So I'm stuck again.