I want to make contenteditable div with bold and italic options to display content in another div on keyup with the same options. I managed to display text, but not options. Please help
html:
<button onclick="document.execCommand('bold');">B</button>
<button onclick="document.execCommand('italic');">I</button>
<div id="textarea" contenteditable></div>
<div id="textarea-show"></div>
jquery:
$('#textarea').keyup(function() {
$('#textarea-show').html($(this).text());
});
css:
#textarea { background-color: #fff;
border: 1px solid #ccc;
color: #555;
font-size: 14px;
height: 34px;
width: 450px;
}
#textarea-show{font-size: 2rem;
color:#666;
height:50px;
border: 1px solid #ccc;
width: 450px;
}
example:https://jsfiddle.net/gqmLtct7/1/
You can add two classes, one let's say bold
and the other italic
, style them and toogle them on click of the buttons to activate/deactivate the bold/italic (You can run the code snippet below or you can also find the updated jsfiddle here):
UPDATE
After the OP's comment, as he wanted to add the bold and italic only to selected text, I've updated my answer a little bit.
The updated jsfiddle.
And the updated code:
$('#textarea').keyup(function() {
$('#textarea-show').html($(this).text());
});
$('#bold_btn').on('click', function() {
//$('#textarea, #textarea-show').toggleClass('bold');
document.execCommand('bold');
var text = document.getElementById('textarea').innerHTML;
$('#textarea-show').html(text);
});
$('#italic_btn').on('click', function() {
//$('#textarea, #textarea-show').toggleClass('italic');
document.execCommand('italic');
var text = document.getElementById('textarea').innerHTML;
$('#textarea-show').html(text);
});
#textarea {
background-color: #fff;
border: 1px solid #ccc;
color: #555;
font-size: 14px;
height: 34px;
width: 450px;
}
#textarea-show {
font-size: 2rem;
color: #666;
height: 50px;
border: 1px solid #ccc;
width: 450px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='bold_btn'>B</button>
<button id='italic_btn'>I</button>
<div id="textarea" contenteditable></div>
<div id="textarea-show"></div>