Jump to content

Introducing the contenteditable attribute in HTML5

+ 1
  adfm's Photo
Posted Feb 26 2010 03:52 PM

Get to know the contenteditable attribute in HTML5 with this excerpt from Ben Henick's HTML & CSS: The Good Parts.


The HTML5 specification adds a number of new global attributes to HTML, including contenteditable, which is already supported by most modern browsers. It’s mainly intended for providing in-browser rich-text/WYSIWYG editors—the kind of editing interfaces you might find in browser-based blog-authoring tools, for example.

The contenteditable attribute essentially enables you as an author to specify that particular parts of a page (the contents of particular elements) are editable. Within those editable parts of the page, users can potentially perform actions like selecting text, cutting and pasting, and moving text (including by dragging and dropping it), as well as changing the character formatting of text to appear bold or italic, or in a different color, or even actions like adding hyperlinks.

Just setting the contenteditable attribute on a particular element won’t cause a browser to actually expose any obvious editing controls to the users. However, it generally will enable users to at least perform actions that have common, familiar keyboard shortcuts (for example, Ctrl-X to cut, Ctrl-V to paste, or Ctrl-B and Ctrl-I for bold and italic). Some browsers even provide a text-editing context menu that’s available by right-clicking in a contenteditable area; this may add a few additional character-formatting actions that don’t have common keyboard shortcuts, such as changing the font size or color of selected text.

It’s possible that other browsers will follow suit and expose more contenteditable text-editing actions (such as, say, an action for easily adding hyperlinks) through a related context menu. However, all that being said, if you want to provide an in-browser user interface for performing editing actions in contenteditable content, you’ll also need to write some programming (scripting) in Javascript. For example, you can easily add a button to a page allowing users to make selected text bold (rather than forcing them to use a keyboard shortcut), but to make it work, you’ll need to add some scripting that associates your button with the action you expect it to perform. (The HTML5 specification provides a number of APIs to facilitate scripting in combination with the contenteditable attribute, but I won’t go into the details here.)

Another limitation of contenteditable is that, on its own, it provides no means for users to actually save the contents of any pages they’ve edited. That’s something else for which you, as an author, will need to provide an interface.



Tags:
0 Subscribe


0 Replies