Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To insert an image at cursor position in tinymce

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

like image 267
Mohan Ram Avatar asked Mar 04 '11 09:03

Mohan Ram


2 Answers

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
like image 186
Thariama Avatar answered Sep 19 '22 23:09

Thariama


@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.)

like image 34
tgray Avatar answered Sep 20 '22 23:09

tgray