I have a div that acts as a WYSIWYG editor. It acts as a text box but renders Markdown syntax within it to show live changes.
Issue: When typing letters, the caret position is reset to the beginning of the div.
const editor = document.querySelector('div'); editor.innerHTML = parse('**dlob** *cilati*'); editor.addEventLis tener('input', () => { editor.innerHTML = parse(editor.innerText); }); function parse(text) { return text .replace(/**(.*)**/gm, '****') // bold .replace(/*(.*)*/gm, '**'); // italic }
div { height: 100vh; width: 100vw; }
Codepen:https://codepen.io/ADAMJR/pen/MWvPebK
Markdown editors like QuillJS seem to be able to edit child elements without editing the parent element. This avoids the problem, but I'm now sure how to recreate that logic with this setup.
Question: How to prevent the caret position from being reset when typing?
renew: I've managed to send the caret position to the end of the div on each input. However, this still essentially resets the position. https://codepen.io/ADAMJR/pen/KKvGNbY
What most rich text editors do is keep their own internal state, update it on key events and render a custom visual layer. For example:
You need to get the cursor position first, and then process and set the content. Then restore the cursor position.
Restoring the cursor position is the tricky part when there are nested elements. Additionally, you will create new
and
elements every time and the old ones will be discarded.