-1

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();
}

1 Answers1

0

Take a look at window.getSelection(), selection.getRangeAt(), and document.execCommand, but it's a very big mountain you're going to climb.

Here's a simple starting point...

var sel = window.getSelection();
var range = sel.getRangeAt(0);

var range0 = range.cloneRange();

range.collapse(true);
document.execCommand('insertText', false, '!!!START!!!');

sel.removeAllRanges();
sel.addRange(range0);
range0.collapse(false);
document.execCommand('insertText', false, '!!!END!!!');

See https://jsfiddle.net/Abeeee/o0e481q3/1/ for a running example

user1432181
  • 918
  • 1
  • 9
  • 24
  • I was able to build a WYSIWYG editor with execCommand, but it is deprecated at this point and I am trying to avoid it, is there any other way? here is a working example of the [WYSIWYG](https://studiodenali.github.io/comma/docs/editor/), this is the [original](https://studiodenali.github.io/comma/docs/editor/) that I want to transfer into div – Jakub Klapka Dec 14 '21 at 17:10
  • But thanks, I will try that, that is exactly what I need – Jakub Klapka Dec 14 '21 at 17:14
  • See https://stackoverflow.com/questions/60581285/execcommand-is-now-obsolete-whats-the-alternative – user1432181 Dec 14 '21 at 17:31