8

Both the button and the div have the same 'onclick' code, yet the execCommand only seems to work on the button. Is there any way I can make it work when pressing the div?

Here's my fiddle: http://jsfiddle.net/foreyez/ZzL8y/

<button onclick="document.execCommand('bold',false,null);">Bold</button>
<div onclick="document.execCommand('bold',false,null);" style='border:1px solid black;width:50px;'>Bold</div>

<div id='input' contenteditable='true'>
    select some of this text and then hit one of the buttons above
</div>

Shai UI
  • 50,568
  • 73
  • 204
  • 309
  • Im guessing it doesn't work with the div because you lose focus and selection. With the button the focus is kept. – DeadAlready Sep 21 '12 at 06:38

3 Answers3

29

You need to prevent the mousedown event on your div because it steals the focus:

Updated fiddle

Konstantin Dinev
  • 34,219
  • 14
  • 75
  • 100
1

See this fiddle :- http://jsfiddle.net/ZzL8y/4/
This is not the complete answer but these links might help you:-

1> set execcommand just for a div

2> select all text in contenteditable div when it focus/click

Community
  • 1
  • 1
Pranav
  • 8,563
  • 4
  • 26
  • 42
0

For Firefox, it's necessary to set contenteditable = true before execCommand.

For IE it is not necessary.