What is it?
This is a few examples of how one might extend jQuery to make the contentEditable a more manageable component of the web.
For convenience I am just going to show the web-standards, so one will need workarounds for IE < 9.
Why is it important?
flag is one of the few ways to get WYSIWYG styling on the
web. Many editors are based on it, such as
bootstrap-wysiwyg among others.
has numerous fundamental problems, as Nick Santos
Why ContentEditable is Terrible Or: How the Medium Editor Works.
Arguably the polymer-project will provide us with an alternative, but we do not appear to be there yet.
So for the moment we are stuck with this beast. So here are some jQuery functions that illustrate how it works and may make it more manageable.
There is nothing limiting these examples to jQuery, of course.
What is a contentEditable?
One can turn a DOM element into a
one by setting the
So once you have the
attribute set, you can edit the
This is fine if one is just entering text. The problem becomes if you want to interact with it.
The primary sources of interaction
The primary interface to the caret and selection of a
. This function returns a
From this selection instance we can get one or more
corresponding to a selection or caret, as shown below.
Are we a caret?
First, here is how we determine if we are looking at a caret:
A range is
if the start and end of the range are the same point.
This is a caret.
Where is the caret?
The positioning of the caret is relative to an arbitrary number of nodes (we
are after all editing a
). So it is straightforward but not
obvious how to determine where said caret is.
Where is the caret?
Sometimes you want to get the
that indicates where the caret is.
For example, you may want this to restore the location after losing focus.
Sometimes you want to know if the Caret is at the start or at the end of the editable.
Other times you may want to know if the caret is on the first or last line:
Putting it all together
Here it is all fiddled together:
Moving the Caret about
Getting information out is one problem. Putting information in is another and, alas, beyond the scope of this article.
Nonetheless, here are a few examples.
We can move the caret to a given place by creating a range and collapsing the selection to one end of the other — creating a caret.
More generally, if you have a range already:
You can find most of the above on StackOverflow, so this is really a coalescence. I hope you find it helpful.