Friday, December 17, 2010

The trouble with contenteditable and WYSWYG editors..

If you want to implement some type of WYSWYG editors, there are several options.  You can try out CkEditor (, which seems to be a re-write of the popular FCkEditor.  It's still 300kB gzip'd, and it has a lot of plug-ins.  You can also TinyMCE and WymEditor, and neither seem optimal since they add so many extra HTML tags and add to the code base.  There's WysiHat, which is used in Basecamp and developed by, but primarily leverages Prototype so JQuery/MooTools frameworks are out.

Enter the 'contenteditable' attribute, which lets you turn any DOM element into an editable field.  You can bold, highlight, italicize and the browser automatically adds the appropriate HTML tag.  The challenge of course is that different browsers add different tags when the Enter button is pressed.  The approach listed here is to intercept the Enter key and insert <br> tags to avoid cross-browser issues:

There isn't an answer on Stack Overflow threads about what to do with the browser to get the cursor position to be move to be situated after "<br>" tags are inserted.  I looked through the CKEditor source code and there's a specific plug-in called _source/plugins/enterkey/plugin.js that tries to deal with the issue. It looks like what ends up happening is that not only is a <br><br/> is added but also an extra bogus <br> is added, in addition to a <span>&nbsp;</span> gets inserted.  The code gets even more convoluted when you start working with IE and Opera browsers, so this general approach just seems a bit difficult in geneal.

The solution may be to post-replace these tags instead:

No comments:

Post a Comment