Search code examples
javascriptjquery

Make selected text bold/unbold


I'm wrapping the selected text in span tags, when you click a button. If I then select a different piece of text and click the button, that text also gets wrapped in tags. However, when I select a piece of text that's already wrapped in span tags, I'd like to remove those tags to unembolden the text, instead of wrapping those tags in more tags.

HTML

<div contenteditable="true" class="textEditor">Some random text.</div>

<a href="#" class="embolden">Bold</a>

JS

$('.embolden').click(function(){
    var highlight = window.getSelection();  
    var span = '<span class="bold">' + highlight + '</span>';
    var text = $('.textEditor').html();
    $('.textEditor').html(text.replace(highlight, span));
});

JSFiddle Demo

I'm probably getting greedy with this request but I select just part of a piece of text that's already wrapped in span tags, but not all of it, I'd like to close the original tag at the start of the selection, open a new tag right after that, then close the new tag at the end of the selection and open a new tag after that.


Solution

  • Why you are trying to bold text doing it by hand when you can use built in feature. Modern browsers implements execCommand function that allows to bold, underline etc. on text. You can write just:

    $('.embolden').click(function(){
        document.execCommand('bold');
    });
    

    and selected text will be made bold and if it's already bold, the text styling will be removed.

    A list of commands and a little doc can be found here. (More about browser support here).

    $(document).ready(function() {
      $('#jBold').click(function() {
        document.execCommand('bold');
      });
    });
    #fake_textarea {
      width: 100%;
      height: 200px;
      border: 1px solid red;
    }
    
    button {
      font-weigth: bold;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button id="jBold"><b>B</b></button>
    <div id='fake_textarea' contenteditable>
      Select some text and click the button to make it bold...
      <br>Or write your own text
    </div>