2012. augusztus 31., péntek

HTML contenteditable - Basics

What is it?

Recently, I have got the opportunity to work with HTMLElements with the attribute contenteditable set (to true if you like it more). This is not over-complicated:
<div contenteditable></div>

<!-- or if you prefer to be more expressive -->

<div contenteditable='true'></div>
Quiet simple, right? =)
It is like a textarea but it is a HTMLDivElement - actually, the prototype object of the object is HTMLDivElement but that is JavaScript/DOM stuff, we don't need that for now.

So the question arises: why would we want to use a contenteditable element instead of a textarea?

Pros:

  • Styling is easier
    It is way much easier to align, position, resize, etc. Since you can work with a div (or section or article or span or whatever...) it is way much easier to maintain the element itself.
    Also, you can forget !important rules in your stylesheets.
  • (X|HT)ML inside
    You can overwrite the browser's default behaviour and write your own text (or in my case Script/screenplay) editor. Like tinyMCE

Kontras:

  • You have just found any enemy. Why? The default behaviour might be/is different in each browser. That just sucks, right? Browser War II... (I am using Webkit [Chrome/Maxthon/Safari])
    So you must write a ridiculously (okay, not that much) massive state-machine which overwrites these default behaviours. (if you want to be the employee of the YEAR at the company, you have good chances now! =D )
  • Key events are not firing up on the contenteditable's children elements when working with (X|HT)ML inside
    This is really weird so far, since the mouse events work just fine but the key events... Not a chance in Chrome 21... You might want to give it a try: jsfiddle here.
    So you will have to have a solution for these type of problems. I wrote a small workaround for that eventHandler context issue, it is really basic stuff with jQuery and it is only a first draft but you get the idea. =) And the fiddle is here.

Writing in a contenteditable element

This is the worst part.. You have click on it (place the focus inside), and you're done! =D Just like the textarea, just like that.

Getting the contents of a contenteditable element

You have some ways to do that, I prefer the DOM way for this one since it is very very simple:
//[element] might be a context inside an event handler function refered as 'this'
element.textContent;
You can also use jQuery to achieve the same result:
//[element] might be a context inside an event handler function refered as 'this'
$(element).text();
You just saved 2 function calls with the DOM way but that doesn't really matter.

So, these are the basics of the contenteditable's, quiet simple stuff, just to get you used to it. =)
Let me know if I should write more about how to do some cool stuff with it. Like XML/HTML stuff inside. It can be awesome if you are over the hatred... =D Next »