Chances are you have tried some rich-text editors embedded in webpages, like TinyMCE and others. In the past, it used to be quite the task to create tools like these. This changed with the introduction of the HTML 5 «contentEditable» attribute. Now, you can with little effort create your own basic rich-text editor.
The «contentEditable» attribute can be set to true or false on any element and will enable or disable design mode for the element. In short, design mode means that the user can edit the content of the element.
In this example I’ve created a simple text-editor. There are buttons to toggle «bold» and «italic» styles on any selected text. When the user clicks one of the buttons or changes the text, the content gets saved.
To create this, the first step is to enable design mode on an item. To do this we add the «contentEditable = true» attribute to, in this case, a div element.
<section id="editbox" contenteditable="true"> .. </section>
Then to apply the styling we need a bit of CoffeeScript. Since this demo has quite a bit of script I’ll draw your attention to the important bit, the «document.execCommand». This method takes one of several commands, in our case “bold” or “italic” and applies this to the selection. For a complete reference of the available commands see this article over at Mozilla.
To set the selected text to bold you only need one simple command.