Search code examples
javascriptjqueryhtmlwysiwyg

contenteditable .execCommand() not firing?


Im experimenting on a custom WYSIWYG editor using contenteditable. I'm using the following code to make the selected text bold:

$('.wysiwyg-b').click(function() {
    document.execCommand('bold',false,true);
    alert('hi');
});
<li class="wysiwyg-b" title="Bold"><img src="images/icons/black/png/font_bold_icon&16.png"> </li>

And it looks like this:

bold

My problem is, the text is only made bold when I click on the image(B), not when I click on the blue surrounding area....but the alert does. What could be causing this issue?

Here is a fiddle http://jsfiddle.net/3b4QM/ I changed the image to a B because the path was broken.

console.log(this) 

returns

<li class="wysiwyg-b" original-title="Bold">

Solution

  • I faced the same problem when I built up Froala Editor (https://froala.com/wysiwyg-editor). It happens because you loose the selection when you click the surroundings. Placing a button inside the <li> will solve the problem. Just make sure the button fits the entire <li>.

    See http://jsfiddle.net/xdCjD/2/

    In HTML:

    <div id="apt-wysiwyg">
        <ul>
            <li class="wysiwyg-b" title="Bold"><button><img src="images/icons/black/png/font_bold_icon&16.png"></button></li>
        </ul>
    </div>
    

    In CSS, remove the padding from li and set it to the button

    #apt-wysiwyg li button {
        padding: 5px;
        height: 30px;
        width: 30px; 
        background: transparent;
        border:none;
    }