Reputation: 24305
I'd like to make a simple text editor to allow people to make the font bold, italicized or underlined. I'm a little confused on how to use the "active" class on twitter bootstrap's buttons to toggle functions such as adding different font styles to words in a textarea.
Here's my HTML:
<span class="btn-group" data-toggle="buttons-checkbox">
<button class="btn btn-bold">Bold</button>
<button class="btn btn-italics">Italics</button>
<button class="btn btn-underline">Underline</button>
</span>
<textarea></textarea>
here's my JS:
$('.btn').click(function(){
if($('.btn-bold').hasClass('active')){
$('.btn-bold').toggle(
function() {
$('textarea').val($('textarea').val()+"<span style='font-weight:bold'>");},
function() {
$('textarea').val($('textarea').val()+"</span>");
}); //toggle
} //if
}); //click
I think i need to have code like this for each font-style: bold, italics, underline I toggle. But as you can see what I have for just making text bold is quite verbose (not to mention doesn't work) so there has to be a better way. Any thoughts would be greatly appreciated.
Upvotes: 4
Views: 3429
Reputation: 75379
A better way to go about editing content would be to use the contentEditable
attribute, since it has a great support across browsers and a great selection of commands (execCommand
) one can execute to edit content out, more information here on the execCommand
.
Here is a short demo i made about how to go about it:
Relevant code:
JS
var current;
$(function() {
$("div[contenteditable]").focus(function() {
current = this;
});
// bold
$('.btn-bold').click(function() {
document.execCommand('bold', false, null);
$(current).contents().focus();
});
//italics
$('.btn-italics').click(function() {
document.execCommand('italic', false, null);
$(current).contents().focus();
});
//underline
$('.btn-underline').click(function() {
document.execCommand('underline', false, null);
$(current).contents().focus();
});
});
Upvotes: 3