Search code examples
javascripthtmlxhtmlwysiwyg

Online WYSIWYG editor using a div


I'm trying to create a WYSIWYG editor using a div, just like Google Docs works (as far as I know). I am aware there are other, easier solution for editors, but all have one thing in common: they output terrible HTML thanks to the Javascript execCommand() function. I really need it to output clean HTML (and the same HTML across browsers), so therefore I'm thinking about writing my own editor with a regular div and some Javascript (to record click and keypresses etc.) Before I do that though, I have a couple of questions:

  • Does the editor I'm looking for (one that outputs the same, clean HTML across browsers) already exist?
  • Am I mistaken that it is possible to write this?

Thanks a lot!

Edit: I think I should have been clearer on this: I don't consider existing WYSIWYG editors (like TinyMCE or CKEditor) an option, because (and please correct me if I'm wrong) they use the Javascript execCommand() function. This (especially in combination with an iFrame in design mode, which they both use), outputs different, illogical HTML in different browsers. For example: a simple enter in Safari causes it to create a div, instead of adding a <br /> tag or create a new paragraph (<p>). Furthermore: making text bold causes Mozilla to add <span style="font-weight: bold">, Internet Explorer and Opera to add <strong> and Safari to add a <b> tag. Not to mention the tricks some browsers pull by adding their name to tags (Safari I'm looking at you, I don't like <span class="Apple-style-span">). Because there's no way to change all these strange behaviors, it's very hard for me to make the site look consistent.

That's the reason I'm thinking about writing my own alternative: cross-browser compatibility and consistency...


Solution

  • Creating an editor from scratch is a massive undertaking because of the sheer number of browser quirks and bugs with in-browser editing. I've done it several times for various niche projects. My advice would be to start with either TinyMCE or CKEditor as a base and extend them. Both have had unbelievable amounts of development time poured into them over several iterations to get them as good as they are now. Try taking a look at their bug trackers to get an idea of what they have to contend with. Both have decent options for extension, so you could write your own formatting commands to replace document.execCommand() and in both you can add buttons/tools to the toolbar and context menus.

    Self-promotion alert: Another option for the future is to use the commands module I'm working on for my Rangy library. It's some way off completion but will initially have replacements for inline formatting commands offered by document.execCommand(), and will allow control of the tags/CSS it produces. Rough early demo here: http://rangy.googlecode.com/svn/branches/1point2/demos/commands.html