7

The document.execCommand() has been obsoleted [DOC]. So, Making WYSIWYG editor is not that easy in 2020. After reading a lot of articles and answers I just find, Most of the answers (developers) prefer to use :

  • document.createRange()
  • window.getSelection()
  • appendChild
  • insertBefore
  • nextSibling.
  • replaceChild, etc

But how? They didn't give any example. I want to make the "Voldemort" word bold after clicking on the B button. I just need an idea of the workflow.

<div class="block-editor">
  <!-- editor control -->
  <div class="block-editor-control">
    <ul>
      <li data-action="bold"> B </li>
    </ul>
  </div>

  <!-- editor content's -->
  <div class="block-editor-content">
    <div class="block-editor-block" contenteditable="true" role="group">
       Voldemort is back
    </div>
  </div>
</div>
Tahazzot
  • 1,224
  • 6
  • 27
  • This article: https://medium.com/@jitubutwal144/three-different-ways-to-build-inline-content-editor-using-javascrpit-d58c2edac9cb appears to have the example that you are looking for. – Three D Fish Dec 27 '20 at 18:41

1 Answers1

1

First, detect Ctrl+B key press (keypress, ctrl+c (or some combo like that)). After that:

  1. Get the selection range: https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection.
  2. Insert <span> at beginning of the range, and insert </span> at the end of the range
  3. Set the span element's font weight to bold.
Endothermic_Dragon
  • 1,147
  • 3
  • 13
  • How to insert the span on the specific char position – Tahazzot Jan 06 '21 at 17:33
  • Hey, I just realized that Ctrl+B, Ctrl+U, and Ctrl+I shortcuts all work in Chrome and Microsoft Edge. What browser are you using such that you are facing this issue? I will need to download it to troubleshoot. – Endothermic_Dragon Jan 06 '21 at 18:15
  • You don't need to worry about the keyboard shortcut. I said when someone clicks on a specific button like here I have a button named B(keyboard shortcut not necessary). I just need the main concept of how to insert the span on the specific char position – Tahazzot Jan 06 '21 at 18:18
  • So first you get the beginning and the end of the range. Next, you insert the string `""` at the end. After that, you insert the string `""` at the beginning. All of this can be done with javascript's slice function - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice. – Endothermic_Dragon Jan 06 '21 at 19:58