Using contentEditable in Firefox: 'bold' renders correctly, but html code is incorrect
Asked Answered
R

2

1

I'm trying to write a wysiwyg editor using a contentEditable div, and am having trouble in Firefox when dealing with bold (and italic).

When all text in the div is selected, execCommand('bold') works in the div, but when I try to grab the HTML of that content, the HTML does not reveal any formatting.

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

<script type="text/javascript">
window.onload = function () {

    var output = document.getElementById('output');
    var input = document.getElementById('input');

}
</script>
<body>
<button onClick="execCommand('bold', false, null);output.value=input.innerHTML;">Bold</button>
<div style="width: 300px; border: 1px solid #000000;">
<div id="input" contenteditable="true">Some editable text</div>
</div>
<textarea id="output"></textarea>
</body>
</html>

Please try the following:

  • Select the word "Some" only. Click the Bold button. This will make the text bold, as expected. The HTML output uses <span style="font-weight:bold;"> to bold the word, which is somewhat unfortunate (it's <b> in Safari, Chrome), but nonetheless does the job.
  • Select the entire phrase "Some editable text" (either manually or using CTRL-A). Click the Bold button. While the contentEditable text is bold, as expected, the HTML output does not have the bold formatting applied.

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

Recusant answered 5/8, 2011 at 22:14 Comment(1)
In Firefox 5 this is what I get as the html: <div contenteditable="true" id="input" style="font-weight: bold;">Some editable text</div>. Since the whole input has had bold applied to it, it applies it as a style to the input instead of creating a span.Intensifier
R
5

Here's a jsFiddle for your original code: http://jsfiddle.net/Bv2Ek/

The issue is that Firefox is adding font-weight: bold to the style attribute of the editable <div> element to make all of it bold, which is quite a reasonable thing to do. If you would rather it used <b> or <strong> elements to apply the boldness, you can use the StyleWithCSS command first. Add the following to your script:

function bold() {
    document.execCommand('StyleWithCSS', false, false);
    document.execCommand('bold', false, null);
}

And your button becomes:

<button onClick="bold(); output.value=input.innerHTML;">Bold</button>

jsFiddle example with amended code: http://jsfiddle.net/Bv2Ek/1/

Radiotelephony answered 7/8, 2011 at 11:40 Comment(0)
F
0

If... that's IF using jQuery.

After exec command:

$('b').contents().unwrap().wrap('<strong/>');
Ferry answered 10/6, 2014 at 19:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.