8

I am using following codes to fetch the conent of tinymce.

tinymce_content=tinyMCE.get('txt_area_id').getContent();
updated_content=tinymce_content+"<img src="sample.jpg">";

By using above codes i am inserting image inside tinymce content.

Question: How to insert image in the cursor position inside tinymce (ie) How to predict cursor position and split the content to insert image between fetched content.

Thanks in advance

Mohan Ram
  • 8,345
  • 25
  • 81
  • 130

2 Answers2

22

This will insert an image node at the selected spot (cursor position) in a tinymce editor

var ed = tinyMCE.get('txt_area_id');                // get editor instance
var range = ed.selection.getRng();                  // get range
var newNode = ed.getDoc().createElement ( "img" );  // create img node
newNode.src="sample.jpg";                           // add src attribute
range.insertNode(newNode);                          // insert Node
Thariama
  • 50,002
  • 13
  • 138
  • 166
  • 3
    Great, whenever i felt struggle in tinymce, i remember thariama Thank u – Mohan Ram Mar 04 '11 at 12:03
  • glad to have been able to help – Thariama Mar 04 '11 at 12:13
  • Just to make this already awesome post a little more clear... To refresh the image and make sure it renders correctly you must make sure that your creating the element in tinyMCE's DOM not the window DOM. So if your using `createElement` make sure you do something like `opener.tinyMCE.selectedInstance.getDoc().createElement`. – Stewart Jan 29 '13 at 04:45
  • and that is exactly the same as ed.getDoc().createElement – Thariama Jan 29 '13 at 07:02
  • Hi Man, I have added a question linked to your answer. Can you please give me comments. Here is the question. [How to add style attribute to an image added with selection.getRng(); in TinyMCE](http://stackoverflow.com/questions/33960835/how-to-add-style-attribute-to-an-image-added-with-selection-getrng-in-tinymce) – Kamran Nov 27 '15 at 15:48
10

@Thariama's answer worked fine for me in Chrome, but not in IE. I had to modify it to the following to get it to work in both browsers:

var ed = tinyMCE.get('txt_area_id');                // get editor instance
var newNode = ed.getDoc().createElement ( "img" );  // create img node
newNode.src="sample.jpg";                           // add src attribute
ed.execCommand('mceInsertContent', false, newNode.outerHTML)

(IE was telling me that range did not have an insertNode method.)

Community
  • 1
  • 1
tgray
  • 8,826
  • 5
  • 36
  • 41
  • Both solutions dont work for me. My IE says: "SCRIPT16389: Erro não especificado." wich means "Error not specified in english... Using IE9 and tiny 3.4 – Filipiz Sep 15 '12 at 19:05
  • I am using tinymce 4.0 . It is working fine in IE10, but getting following error in IE11 SCRIPT16389: Incorrect function. File: tinymce.min.js, Line: 8, Column: 20915 Can you please help me out. – Naresh.P Nov 19 '14 at 07:14