How to create a RichText Editor in HTML/JS without document.execCommand?

Viewed 1098
1 Answers

After having experimentated I found a way to proceed with vanilla HTML/CSS/JS, here is my JSFiddle :

https://jsfiddle.net/y9qzejmf/1/

function insertTag(tag_name) {

  let editor_textarea = document.getElementById("editor_textarea");

  let selection = null;

  if (editor_textarea.selectionStart == editor_textarea.selectionEnd)
    selection = editor_textarea.selectionStart;
  else
    selection = editor_textarea.value.slice(editor_textarea.selectionStart, editor_textarea.selectionEnd);

  switch (tag_name) {
    case "strong":
      tag_name = "strong";
      break;

    case "italic":
      tag_name = "i";
      break;

    case "underline":
      tag_name = "u";
      break;

    case "code":
      tag_name = "code-tag";
      break;

    default:
      tag_name = null;
      break;
  }

  if (tag_name != null)
    editor_textarea.setRangeText(`<${tag_name}>${selection}</${tag_name}>`);
}
Related