World Simplest HTML5 WYSIWYG Inline Editor
I am pretty new to web/JavaScript development, and often quickly reach for Google in order to find out how to do things.
Recently I needed to add the ability to do some pretty basic in-page editing of content. I didn’t want to use iFrame’s, i didn’t want a hugely featured editor, literally some pretty basic tools to be able to edit content, bold, italic, h1, h2 and so on.
After a fair bit of Googling, it seemed that there wasn’t a hope! all the plug in’s i found just seems unnecessarily complicated so, in a fit of self-importance, i decided i could do it myself. i’d end up with the editor i wanted, and code that i fully understood. Granted, it wasn’t likely to be an easy job, but hey, why would i code anything if there was an easier option?
To my surprise, as it turns out, it’s so simple, it’s almost a joke! all the tools are already available, all you need to do it tie them together with some really simple JavaScript, and it works!
There are two things you need, the first is
{% highlight javascript %}contenteditable{% endhighlight %}
contenteditable tells the browser that this item (a div for example) can be edited inline. You can do all the normal text editing here with ctrl-b for bold, ctrl-i for italics etc, but it’s fairly limited.
The second thing you need is a special function called
{% highlight javascript %}execCommand{% endhighlight %}
execCommand actually allows us to do some fairly complex stuff with the contents of the **contenteditable **area, and all in a really compliant way!
If you want to read what it can do in detail, check out The Mozilla Docs
Essentially, execCommand takes three parameters:
Command Name – the name of a command
ShowDefaultUI – not implemented, and best set to false
ValueArgument – optional for some commands so for example, using the command ‘bold’ will make the currently selected text turn bold with a tag!
ValueArgument can be set to null in all but one case. When you want to set a tag for a line of text (h1, h2 for example) you need to use the formatBlock command, and put the tag you want in the ValueArgument (without angle-braces).
Now this is simple enough, but to make life even easier, a single click handler and a data-attribute on each link allow us to have one very simple function to handle everything.
The demo uses bootstrap and jQuery, but only to make the code a little more brief, and could all easily be done in plain old JavaScript.
[CodePen height=300 show=result href=idjCG user=barney-parker ]
EDIT: CompuSam suggested using {% highlight javascript %}href='javascript:void(0)'{% endhighlight %} instead of {% highlight javascript %}href’#'{% endhighlight %} to stop and unwanted page movements etc….