Question

I have the following code:

<div contenteditable="true" style="height:100px;width:100px;border:1px solid; " class="editor"></div>
<a class='bold' style="height:10px;width:10px;">B</a> 

$(function(){
    $("a.bold").on("click",function(){
        document.execCommand('bold',false,true);
    }) 
})

When I clicked on the B link the content in the contenteditable div was not emboldened. As can be seen from the jsfiddle here http://jsfiddle.net/JeremyHuang_Stern/487YF/

However, when I used a button instead of a link to do the same thing the problem disappeared. As can be seen from this fiddle http://jsfiddle.net/JeremyHuang_Stern/2QG26/

What is causing the difference here ?

Was it helpful?

Solution

The link steals selection from the text on mousedown. Prevent the default behavior to avoid this.

$('a.bold').on('mousedown', function(event) {
    event.preventDefault();
    document.execCommand('bold', false, false);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top