A little while ago, I was working on a project that required the user type in some formatted data. Usually I just go the Markdown route (which is actually what the blog post is written in), however I decided to find a WYSIWYG editor that would make it easier.

I looked around for a while, but all the editors I could find were either huge, or required jQuery. So I set out to create my own. So I read up on the document.execCommand function and the contenteditable attribute.

Now what the contenteditable attribute does, is it makes any element editable. It’ll keep all the same styling as well. This allows us to make a div editable. However, there’s no styling inside the div. So here comes along document.execCommand.

The document.execCommand function is basically made for WYSIWYG editors. It accepts commands relating to the styling of the currently selected element. So you can send the command to make the current element a header, and it’ll do that. Or a list, bold, underline, etc. You can even undo and redo.

So I created the HTMl5WYSIWYG Editor. It allows you to create simple editors, then retrieve the contents as HTML. The usage is pretty simple, being just

var wysiwyg = new WYSIWYG('#editor');

With your wysiwyg object, you can do a few things. If you override the function onChange you can detect when the user changes anything. You can also call getHTML to get the currrent content.

~GitHub ~Demo