Search code examples
javascripthtmlwebwysiwygrichtext

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


I'd like to create my own RichText Editor in HTML/JS like so :

https://www.youtube.com/watch?v=cOeTHVlFDYs

But according to the MDN, document.execCommand is now deprecated (https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand), so how to proceed ?

Thanks in advance for your answer


Solution

  • 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}>`);
    }