0

So my newest project requires the use of designMode (or similar methods of creating rich text editors), but I am having difficulty using the default commands. I would much rather insert my own HTML at the location of the selector. For example, I would want inserted images to have an align property (with proper CSS, of course), insert HTML5 video tags, etc. Is there a "preferred" method of doing this (with Javascript or jQuery)?

Thanks!

tundoopani
  • 255
  • 9
  • 21

1 Answers1

1

You don't have to use document.execCommand() for this; it's relatively simple without, and more flexible.

I've provided an answer to a similar question that inserts arbitrary HTML at the current caret position: Insert html at caret in a contenteditable div.

Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • I edited the code so that "window" is replaced with the doc variable. var doc = document.getElementById(editorid).contentWindow; The editorid value is provided. The code works great in firefox and chrome, but not in IE9. :( I included just the js here: http://jsfiddle.net/tNwFD/. I am using designMode instead of contenteditable. – tundoopani Oct 22 '11 at 00:41
  • @tundoopani: You need to use both the window and document objects of the iframe. I updated your code: http://jsfiddle.net/tNwFD/1/ – Tim Down Oct 22 '11 at 10:22
  • Thank you very much! It works in IE now but the HTML is always added at the beginning of the field. :/ – tundoopani Oct 25 '11 at 05:40
  • 1
    @tundoopani: The problem is probably that in IE the selection/caret is destroyed by the time the `click` event of your button is fired. You can work round this by using the `mousedown` event instead, or (better) by making the button unselectable using `unselectable="on"` in IE. – Tim Down Oct 25 '11 at 08:03
  • It seems that using the click event on a div element will also cause the selection/caret to be destroyed by the time the click event is fired. This happens in all browsers. Do you know why this happens with div elements and not buttons? In the meantime, I'll try to use the mousedown event. Thanks! – tundoopani Sep 26 '12 at 06:17