I am working on a markdown editor in HTML and JS, which previously used textarea but I started moving it to a contenteditable div recently due to the limitations it had, tried a lot but I cannot get it working, I just need a basic function to insert markdown ** around a selection, but there seems to be something wrong with contenteditable divs, anyone has any idea how to fix?
function editorInsertFormatting(txtarea, text) {
var selectStart = txtarea.selectionStart;
var selectEnd = txtarea.selectionEnd;
var scrollPos = txtarea.scrollTop;
var caretPos = txtarea.selectionStart;
var front = txtarea.value.substring(0, caretPos);
var back = txtarea.value.substring(
txtarea.selectionEnd,
txtarea.value.length
);
var middle = txtarea.value.substring(caretPos, txtarea.selectionEnd);
txtarea.value = front + text + middle + text + back;
if (selectStart !== selectEnd) {
txtarea.selectionStart = selectStart + text.length;
txtarea.selectionEnd = selectEnd + text.length;
} else {
txtarea.selectionStart = selectStart + text.length;
txtarea.selectionEnd = txtarea.selectionStart;
}
txtarea.focus();
txtarea.scrollTop = scrollPos;
editorLiveParser();
}