Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 738
colmtuite Avatar asked Jan 02 '14 09:01

colmtuite


People also ask

How do you Unbold selected text?

Ctrl + B is the shortcut key to make the selected letters bold or unbold.

How do you Unbold text in Excel?

The CTRL+B key is used to apply or remove bold. It will bold or un-bold the cell when one or more cell is selected. This shortcut works for the new text you type after using it, or you can highlight existing text and then bold it via the shortcut.

How do I make my text bold in typing?

Make text bold . Click Bold. in the Font group on the Home tab. Type the keyboard shortcut: CTRL+B.

How do you Unbold text in HTML?

Use <span> when you want to change the style of elements without placing them in a new block-level element in the document.


1 Answers

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>
like image 60
Łukasz Jagodziński Avatar answered Mar 22 '23 19:03

Łukasz Jagodziński