Search code examples
javascriptjqueryhtmlwysiwyg

Why Does execCommand('bold') Do Nothing?


I'm trying to make a simple WYSIWYG editor but I'm having trouble making text bold. I am able to make text underlined with document.execCommand("underline", false, null); and make text italic with document.execCommand("italic", false, null); but document.execCommand("bold", false, null); does nothing.

I checked the html output and it doesn't add any <b> or <strong> tags to the text either.

This is the HTML:

<button id="underline" type="button">Underline</button>
<button id="italic" type="button">Italic</button>
<button id="bold" type="button">Bold</button>
<div id="editor" contenteditable="true" spellcheck="false"></div>

and here is the jQuery:

$('#underline').click(function() {
   document.execCommand("underline", false, null);
});

$('#italic').click(function() {
   document.execCommand("italic", false, null);
});

$('#bold').click(function() {
   document.execCommand("bold", false, null);
});

Solution

  • This works as far as I can tell. Check out this fiddle: http://jsfiddle.net/om78patL/

    $('#underline').click(function() {
       document.execCommand("underline", false, null);
    });
    
    $('#italic').click(function() {
       document.execCommand("italic", false, null);
    });
    
    $('#bold').click(function() {
       document.execCommand("bold", false, null);
    });
    
    <button id="underline" type="button">Underline</button>
    <button id="italic" type="button">Italic</button>
    <button id="bold" type="button">Bold</button>
    <div id="editor" contenteditable="true" spellcheck="false">test</div>