Insert content at cursor position in tinyMCE editor

Recently I had a requirement to add text and images at the cursor position in tiny editor. Actually I had to implement multiple images attachment with "add to post" button with each uploaded images and when user clicked the button "add to post", the image will be get inserted at cursor position in tinyMCE  editor.

I had gone through tinyMCE  documentation and find the best solution for inserting content and images at the cursor position. So here  I am going to share my experience of it.
You can use the following command to insert the content (text, image or whatever you want) at the cursor position in tinyMCE rich text editor
Insert Text at Cursor position in tinyMCE Editor

tinyMCE.execInstanceCommand(‘textarea_id’,“mceInsertContent”,false,“Text to be inserted”);


In above example, textarea_id is the id of the text area in which you want to insert the content. If cursor is inside that text area then content will be inserted at the cursor position but if this text area does not have focus then content will be inserted in the start of that text area.

Set Cursor at the End of The Text in TinyMCE Editor

You can also set cursor at the end of text in your loaded editor. Use bellow code for this.

tinyMCE.activeEditor.selection.select(tinyMCE.activeEditor.getBody(), true);
tinyMCE.activeEditor.selection.collapse(false);

You may like these posts