Creating a simple WYSIWYG editor with HTML and JavaScript


An updated and better version of this post with a new and better demo can be found here: http://www.kinderas.com/technology/2014/2/18/a-simple-rich-text-editor

Wouldn't it be nice to provide the users of your website with a WYSIWYG rich text editor instead of boring forms and a bunch of textfields? Enter «contenteditable». This is a simple property which can be set on any DOM element, like divs, sections and so on. What it does it making the element writable for the user, directly inline with all your predefines styles and content.
contenteditable="true"
To get set up, set the «contenteditable» property of your selected element to "true". In my demo I'm using a «section» element, but as noted above, you can use any DOM element. And that is it actually. You now have a working rich text editor running on you web-page. You can use the keyboard shortcuts like «cmd+b» to make selected text bold and so on. But wait, there's more.
document.execCommand('bold',false,null);
This simple JavaScript command will allow you to programmatically make text bold and thats not all, there are a dozen of built in commands which can be executed on the selected text, for an overview take a look at the WHATWG specification.

When combining «contenteditable» with the HTML 5 storage APIs you can pretty easily make a powerful rich text editor for your users. Take a look at my simple demo to see how you can accomplish this. As a side note, iOS 5 brings support for «contenteditable» on mobile platforms as well.