Reputation: 4491
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));
});
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.
Upvotes: 9
Views: 49528
Reputation: 1
$(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://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.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>
Upvotes: 0
Reputation: 13354
If you are looking to use the keyboard to bold characters, you can use the following (Mac):
$(window).keydown(function(e) {
if (e.keyCode >= 65 && e.keyCode <= 90) {
var char = (e.metaKey ? '⌘-' : '') + String.fromCharCode(e.keyCode)
if(char =='⌘-B') {
document.execCommand('bold')
}
}
})
Using keyboard to bold character:
Upvotes: 1
Reputation: 3089
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>
Upvotes: 53
Reputation:
Got it, finally:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.emphasized {
text-decoration: underline;
font-weight: bold;
font-style: italic;
}
</style>
</head>
<body>
<button type="button" onclick="applyTagwClass(this);" data-tag="span" data-tagClass="emphasized">Bold</button>
<div contenteditable="true" class="textEditor">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. In malesuada quis lorem non consequat. Proin diam magna, molestie nec leo non, sodales eleifend nibh. Suspendisse a tellus facilisis, adipiscing dui vitae, rutrum mi. Curabitur aliquet
lorem quis augue laoreet feugiat. Nulla at volutpat enim, et facilisis velit. Nulla feugiat quis augue nec sodales. Nulla nunc elit, viverra nec cursus non, gravida ac leo. Proin vehicula tincidunt euismod.</p>
<p>Suspendisse non consectetur arcu, ut ultricies nulla. Sed vel sem quis lacus faucibus interdum in sed quam. Nulla ullamcorper bibendum ornare. Proin placerat volutpat dignissim. Ut sit amet tellus enim. Nulla ut convallis quam. Morbi et
sollicitudin nibh. Maecenas justo lectus, porta non felis eu, condimentum dictum nisi. Nulla eu nisi neque. Phasellus id sem congue, consequat lorem nec, tincidunt libero.</p>
<p>Integer eu elit eu massa placerat venenatis nec in elit. Ut ullamcorper nec mauris et volutpat. Phasellus ullamcorper tristique quam. In pellentesque nisl eget arcu fermentum ornare. Aenean nisl augue, mollis nec tristique a, dapibus quis urna.
Vivamus volutpat ullamcorper lectus, et malesuada risus adipiscing nec. Ut nec ligula orci. Morbi sollicitudin nunc tempus, vestibulum arcu nec, feugiat velit. Aenean scelerisque, ligula sed molestie iaculis, massa risus ultrices nisl, et placerat
augue libero vitae est. Pellentesque ornare adipiscing massa eleifend fermentum. In fringilla accumsan lectus sit amet aliquam.</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function applyTagwClass(self) {
var selection = window.getSelection();
if (selection.rangeCount) {
var text = selection.toString();
var range = selection.getRangeAt(0);
var parent = $(range.startContainer.parentNode);
if (range.startOffset > 0 && parent.hasClass(self.attributes['data-tagClass'].value)) {
var prefix = '<' + self.attributes['data-tag'].value + ' class="' + self.attributes['data-tagClass'].value + '">' + parent.html().substr(0,selection.anchorOffset) + '</' + self.attributes['data-tag'].value + '>';
var suffix = '<' + self.attributes['data-tag'].value + ' class="' + self.attributes['data-tagClass'].value + '">' + parent.html().substr(selection.focusOffset) + '</' + self.attributes['data-tag'].value + '>';
parent.replaceWith(prefix + text + suffix);
} else {
range.deleteContents();
range.insertNode($('<' + self.attributes['data-tag'].value + ' class="' + self.attributes['data-tagClass'].value + '">' + text + '</' + self.attributes['data-tag'].value + '>')[0]);
//Remove all empty elements (deleteContents leaves the HTML in place)
$(self.attributes['data-tag'].value + '.' + self.attributes['data-tagClass'].value + ':empty').remove();
}
}
}
</script>
</body>
</html>
You'll notice that I extended the button to have a couple data-
attributes. They should be rather self-explanatory.
This will also de-apply to subsections of the selected text which are within the currently-targeted element (everything goes by class name).
As you can see, I'm using a class which is a combination of things so this gives you more versatility.
Upvotes: 1
Reputation: 4491
Modern browsers utilize the execCommand function that allows you to embolden text very easily. It also provides other styles like underline etc.
<a href="#" onclick="emboldenFont()">Bold</a>
function emboldenFont() {
document.execCommand('bold', false, null);
}
Upvotes: 0
Reputation: 1018
Something like this should do the trick:
var span = '';
jQuery(function($) {
$('.embolden').click(function(){
var highlight = window.getSelection();
if(highlight != ""){
span = '<span class="bold">' + highlight + '</span>';
}else{
highlight = span;
span = $('span.bold').html();
}
var text = $('.textEditor').html();
$('.textEditor').html(text.replace(highlight, span));
});
});
Upvotes: 1
Reputation: 3326
Copied function from this answer: Get parent element of a selected text
Haven't really perfected this and I think this only works on exact selections but it gives you an idea of how to go around this. The click function checks if the parent element of the current selection has the class 'bold', if so it replaces that element with the original selection again.
jQuery(function($) {
$('.embolden').click(function(){
var highlight = window.getSelection();
var span = '<span class="bold">' + highlight + '</span>';
var text = $('.textEditor').html();
var parent = getSelectionParentElement();
if($(parent).hasClass('bold')) {
$('.textEditor').html(text.replace(span, highlight));
} else {
$('.textEditor').html(text.replace(highlight, span));
}
});
});
function getSelectionParentElement() {
var parentEl = null, sel;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
parentEl = sel.getRangeAt(0).commonAncestorContainer;
if (parentEl.nodeType != 1) {
parentEl = parentEl.parentNode;
}
}
} else if ( (sel = document.selection) && sel.type != "Control") {
parentEl = sel.createRange().parentElement();
}
return parentEl;
}
Upvotes: 3
Reputation: 531
This code goes thru the content of the textEditor and removes all the span tags. It should do the trick.
jQuery(function($) {
$('.embolden').click(function(){
$('.textEditor span').contents().unwrap();
var highlight = window.getSelection();
var span = '<span class="bold">' + highlight + '</span>';
var text = $('.textEditor').html();
$('.textEditor').html(text.replace(highlight, span));
});
});
Upvotes: 0
Reputation: 1467
check this is it what u wanted ???
using
.toggleclass()
(to make all text in text editor class bold only)
Upvotes: -1