How can I (using jquery or other) insert html at the cursor/caret position of my contenteditable div:
<div contenteditable="true">Hello world</div>
For example, if the cursor/caret was between "hello" and "world" and the user then clicked a button, eg "insert image", then using javascript, something like <img src=etc etc>
would be inserted between "hello" and "world". I hope I've made this clear =S
Example code would be greatly appreciated, thanks a lot!
I would recommend the use of the jquery plugin a-tools
This plugin has seven functions:
The one that you need is insertAtCaretPos:
There might be a draw-back: this plugins only works with textarea en input:text elements, so there may be conflicts with contenteditable.
in this code i have just replace html code with (") to (')
use this syntax:
The following function will insert a DOM node (element or text node) at the cursor position in all the mainstream desktop browsers:
If you would rather insert an HTML string:
I've adapted this from my answer to a similar question: How to find cursor position in a contenteditable DIV?
With
contenteditable
you should useexecCommand
.Try
document.execCommand('insertImage', false, 'image.jpg')
ordocument.execCommand('insertHTML', false, '<img src="image.jpg" alt="" />')
. The second doesn't work in older IE.