Search code examples
javascriptjquerycontenteditable

contenteditable default styling


I have the following JSFiddle: https://jsfiddle.net/ta05jk3d/.

It contains a contenteditable div and a button. If you enter some text in the div, it's normal text (not bold or underlined or whatsoever). If you click on the button, the text "test" is added to the div in bold.

What is the problem? If you click on the button, the text "test" appears in bold (and that's ok), but if you enter some text after the bold text, all the other text is also in bold.

Like this:

some text... test the other text I enter after "test" is now also in bold

I want to be able to add a bold text but ONLY if I click the button. The text I enter afterwards may be bold, but just normal text, like this:

text... test some other text...

$('.button').on('click',function(e){
    var content = $('.msg').html();
    $('.msg').html(content+'<strong>test</strong>');
});

Solution

  • You need to put an element or node after the <strong> so that the browser recognises that the cursor should be outside the bold content when the focus is placed back in the contenteditable element:

    $('.button').on('click', function(e) {
      var content = $('.msg').html();
      $('.msg').html(content + '<strong>test</strong>&nbsp;'); // note '&nbsp;'
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    
    <div class="msg" style="border: 1px solid red; padding:10px;" contenteditable></div>
    <button class="button">Add some text</button>