Adventures with contenteditable

The contentenditable attribute offers powerful editing capabilities on nearly any HTML element, allowing far greater formatting options and more streamlined editing environment than a simple textarea. However, it has a few key short comings that require some work to overcome.

Depending on the situation, especially when a rich text editing toolbar is needed, the best solution may be a library like Medium.js, which includes a wide range of editing options and capabilities (although it does require a couple of dependencies). While this and other libraries will also make contenteditable beyond usable, I’ve tied up a couple of the loose ends currently present for a quick or lightweight implementation.

In it’s current incarnation, contenteditable handles empty elements rather poorly: an empty element is automatically deactivated and the cursor cannot be placed inside, even through JavaScript. The solution to this is to detect the backspace key on keyup and insert an empty span into the parent element when it is empty:

This function also prevents the backspace key from navigating the browser when the element is empty, as it normally would. To ensure that empty elements can be focused properly, another short function is required:

This creates an empty span and focuses the element, placing the cursor at the beginning. This code has been tested mainly in Chrome v41, although there shouldn’t be any significant issues with current version of Firefox or Internet Explorer (although IE 11 does exhibit some weird behavior with the cursor).

Leave a Reply

Your email address will not be published. Required fields are marked *