Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add or modify text/ content in contenteditable div without execCommand?

Tags:

javascript

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>
like image 812
Tahazzot Avatar asked Aug 25 '20 05:08

Tahazzot


People also ask

What can I use instead of document execCommand?

The Clipboard API can be used instead of execCommand in many cases, but execCommand is still sometimes useful.

How do I make content editable?

To edit the content in HTML, we will use contenteditable attribute. The contenteditable is used to specify whether the element's content is editable by the user or not. This attribute has two values. true: If the value of the contenteditable attribute is set to true then the element is editable.

What is false about Contenteditable attribute?

The contentEditable property of the HTMLElement interface specifies whether or not the element is editable. This enumerated attribute can have the following values: ' true ' indicates that the element is contenteditable . ' false ' indicates that the element cannot be edited.

Which attribute indicates whether content in a webpage is editable or not?

The contenteditable attribute specifies whether the content of an element is editable or not.


1 Answers

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.
like image 171
Endothermic_Dragon Avatar answered Nov 26 '22 06:11

Endothermic_Dragon