Javascript – Problems with contenteditable in Firefox

contenteditablefirefoxhtmljavascriptwysiwyg

I am working on a Javascript WYSIWYG editor in Firefox. I am using a div with the contenteditable attribute set to true in order to accomplish this (I cannot use a contenteditable iframe for this particular project). This contenteditable div is nested in another div that is not contenteditable. I am encountering the following two problems when using execCommand to apply formatting, including font style and size, as well as bold, italic, and underline:

  • When all text in the div is selected, execCommand simply does not work. execCommand works fine when only part of the text is selected, but does nothing when all of the text is selected.
  • Applying formatting with no text selected yields unexpected results. For example, when calling execCommand('bold') with no text selected and then typing results in bold text being typed until a spacebar is inserted, at which point the bold formatting is lost (until another space is inserted, interestingly enough; then the text becomes bold again).

To see what I mean, please try running the following HTML code in Firefox 3:

<html>
<head><title></title></head>
<body>
<button onClick="execCommand('bold', false, null);">Bold</button>
<div style="width: 300px; border: 1px solid #000000;">
<div contenteditable="true">Some editable text</div>
</div>
</body>
</html>

Please try the following:

  • Select the word "Some" only. Click the Bold button. This will make the text bold, as expected.
  • Select the entire phrase "Some editable text" (either manually or using CTRL-A). Click the Bold button. Nothing happens. This demonstrates the first bug shown above.
  • Hit the backspace key to clear the div. Click the Bold button and begin typing. Type a few words with spaces. This will demonstrate the second bug.

Any ideas on what could be causing these problems and how to work around them would be greatly appreciated!

Best Answer

Interesting. In Firefox 3.6.3, I can't replicate the first problem: selecting all of the editable text and pressing the button toggles boldness as expected. However, the other two issues I do see. They'll be bugs in Mozilla's implementation of contenteditable.

Interestingly, the alternate-words-bold problem doesn't happen if you use designMode rather than contenteditable. I suspect it will solve your other problem too. This involves making the whole document editable, rather than just elements within it:

window.onload = function() {
    document.designMode = "on";
};

If this isn't an option and you need the fine control that contenteditable provides, you'll need to implement your own version of the bold command using DOM manipulation and Ranges. This will be quite involved to get working in IE and non-IE browsers.