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?
There are two things you need, the first is
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
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 <b> 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.
[CodePen height=300 show=result href=idjCG user=barney-parker ]