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.
Ctrl + B is the shortcut key to make the selected letters bold or unbold.
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.
Make text bold . Click Bold. in the Font group on the Home tab. Type the keyboard shortcut: CTRL+B.
Use <span> when you want to change the style of elements without placing them in a new block-level element in the document.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With