Reputation: 2226
I'm trying to follow this answer, but rather than using a button as he does in his jsfiddle, I'm trying to use list items:
http://jsfiddle.net/hqvDT/108/
It looks like it should work, but when I try to select some text and then press B
(for bold), it doesn't actually bold the text.
What's wrong?
HTML:
<div id="myarea" contenteditable="true"></div>
<ul>
<li onclick="MakeBold();">B</li>
<li><i>I</i></li>
</ul>
CSS:
#myarea {
border:1px solid #000;
padding:5px;
height:150px;
width:400px;
overflow:scroll;
}
ul {
list-style: none;
}
ul li {
width: 35px;
height: 35px;
border: 1px solid #ccc;
text-align: center;
line-height: 32px;
font-size: 14px;
color: #999;
cursor: pointer;
display: inline-block;
margin-right: -5px;
font-weight: bold;
font-size: 18px;
}
ul li:hover {
color: black;
}
JS:
function MakeBold() {
document.execCommand('bold', null, false);
}
Upvotes: 4
Views: 36679
Reputation: 390
With mousedown and preventDefault.
HTML:
<div id="myarea" contenteditable="true">Mark a word of this paragraph and bold or italiced it</div>
<ul>
<li id="bolded">B</li>
<li id="italiced"><i>I</i></li>
</ul>
JS:
document.getElementById("bolded").addEventListener("mousedown", function(event){
event.preventDefault()
document.execCommand('bold', false, null)
})
document.getElementById("italiced").addEventListener("mousedown", function(event){
event.preventDefault()
document.execCommand('italic', false, null)
})
codepen: https://codepen.io/harivera/pen/wvodZOR
Upvotes: 0
Reputation: 78630
Clicking on a button does not de-select text selection. Other elements when clicked will deselect the text. Since the text is deselected before the click fires, the text will not be made bold. You will either need to use a button or remember the selected text every time text is selected and deal with the saved selection. I would really suggest sticking with a button.
Upvotes: 0
Reputation: 142921
The problem is that when an element other than a button is clicked, the selection in the textarea disappears.
On way to fix this is to use onmousedown
instead of onclick
, since the mousedown
event is triggered before the text selection is lost.
<li onmousedown="MakeBold()">B</li>
Upvotes: 5