Onclick event on list item

Tags: , , ,



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);
}

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.

<li onmousedown="MakeBold()">B</li>


Source: stackoverflow