JavaScript execCommand and contenteditable Getting started

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

The HTML attribute contenteditable provides a simple way to turn a HTML element into a user-editable area

<div contenteditable>You can <b>edit</b> me!</div>

Native Rich-Text editing

Using JavaScript and execCommandW3C you can additionally pass more editing features to the currently focused contenteditable element (specifically at the caret position or selection).

The execCommand function method accepts 3 arguments

document.execCommand(commandId, showUI, value)
  • commandId String. from the list of available **commandId**s
    (see: Parameters→commandId)
  • showUI Boolean (not implemented. Use false)
  • value String If a command expects a command-related String value, otherwise "".
    (see: Parameters→value)

Example using the "bold" command and "formatBlock" (where a value is expected):

document.execCommand("bold", false, "");          // Make selected text bold
document.execCommand("formatBlock", false, "H2"); // Make selected text Block-level <h2>

Quick Start Example:

<button data-edit="bold"><b>B</b></button>
<button data-edit="italic"><i>I</i></button>
<button data-edit="formatBlock:p">P</button>
<button data-edit="formatBlock:H1">H1</button>
<button data-edit="insertUnorderedList">UL</button>
<button data-edit="justifyLeft">&#8676;</button>
<button data-edit="justifyRight">&#8677;</button>
<button data-edit="removeFormat">&times;</button>

<div contenteditable><p>Edit me!</p></div>

<script>
[].forEach.call(document.querySelectorAll("[data-edit]"), function(btn) {
  btn.addEventListener("click", edit, false);
});

function edit(event) {
  event.preventDefault();
  var cmd_val = this.dataset.edit.split(":");
  document.execCommand(cmd_val[0], false, cmd_val[1]);
}
<script>

jsFiddle demo
Basic Rich-Text editor example (Modern browsers)

Final thoughts
Even being present for a long time (IE6), implementations and behaviors of execCommand vary from browser to browser making "building a Fully-featured and cross-browser compatible WYSIWYG editor" a hard task to any experienced JavaScript developer.
Even if not yet fully standardized you can expect pretty decent results on the newer browsers like Chrome, Firefox, Edge. If you need better support for other browsers and more features like HTMLTable editing etc. a rule of thumbs is to look for an already existent and robust Rich-Text editor.



Got any JavaScript Question?