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:
JavaScript
x
7
1
<div id="myarea" contenteditable="true"></div>
2
3
<ul>
4
<li onclick="MakeBold();">B</li>
5
<li><i>I</i></li>
6
</ul>
7
CSS:
JavaScript
1
31
31
1
#myarea {
2
border:1px solid #000;
3
padding:5px;
4
height:150px;
5
width:400px;
6
overflow:scroll;
7
}
8
9
ul {
10
list-style: none;
11
}
12
13
ul li {
14
width: 35px;
15
height: 35px;
16
border: 1px solid #ccc;
17
text-align: center;
18
line-height: 32px;
19
font-size: 14px;
20
color: #999;
21
cursor: pointer;
22
display: inline-block;
23
margin-right: -5px;
24
font-weight: bold;
25
font-size: 18px;
26
}
27
28
ul li:hover {
29
color: black;
30
}
31
JS:
JavaScript
1
4
1
function MakeBold() {
2
document.execCommand('bold', null, false);
3
}
4
Advertisement
Answer
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.
JavaScript
1
2
1
<li onmousedown="MakeBold()">B</li>
2