paula
paula

Reputation: 13

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

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:

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

Upvotes: 1

Views: 3188

Answers (2)

Shawn Rebelo
Shawn Rebelo

Reputation: 1087

If... that's IF using jQuery.

After exec command:

$('b').contents().unwrap().wrap('<strong/>');

Upvotes: 0

Tim Down
Tim Down

Reputation: 324557

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/

Upvotes: 5

Related Questions