Adding images to TinyMCE using ‘execCommand’

I love TinyMCE. It’s extremely easy to integrate and best of all, it’s open source and thus free.

Some time ago, something stumped my co-worker and I about TinyMCE. We were working on a blog application that included an HTML editor. Along with the editor, we wanted to give the users a chance to upload pictures with their posting. But looking at the general structure of TinyMCE, we realized that TinyMCE was not built to accommodate multiple users (I might be wrong here, but it’s didn’t seem possible without purchasing MCImageManager).

In our application, each user has the ability to upload his own images and should not have access to the rest of the images uploaded by other registered users.

After some investigating of the TinyMCE API, here’s the workaround I found that solved our issues perfectly. Instead of uploading pictures using the editor, we uploaded pictures the traditional way, that is created file upload fields in which the actions for creating folders, etc was done separately. As soon as the user uploaded a picture, it would appear in a table below. The table will contain certain things. As you can see from the picture, a user could perform two different actions on each picture, that is Add or Delete. On the Add icon, I added a small piece of code that will trigger an action when clicked.

Each Add icon is a link in which the href attribute refers to the location the the image uploaded.

1
<a href="http://blogs.matrixsuites.com/UserFiles/Image/4/1184/editable.jpg" class="add">editable.jpg</a>
1
2
3
4
5
$('.add').click(function(){
    var href = $(this).attr('href');
    tinyMCE.execCommand('mceInsertRawHTML',false, '<img src="' + href + '" alt="" />');
    return false;
});

The code example above uses jQuery, but you can modify the section easily to not use a library at all.

This uses the TinyMCE execCommand to insert raw html into the editor. The href attribute contains the image path and the image gets added into the editor easily. An interesting thing to note is the image gets added to the current cursor position in your editor.

2 Responses to “Adding images to TinyMCE using ‘execCommand’”

  1. Dries on November 27th, 2009 at 4:10 pm

    Thank you for sharing this ! I was searching for a way to insert html into my TinyMCE editor.
    Although I find ‘mceInsertContent’ to be faster than ‘mceInsertRawHTML’

  2. javas on February 28th, 2010 at 11:43 pm

    good way. i felt difficult to find “image manager” for any wysiwyg editor. i found nicEdit, but that’s not so good. thank you, for tinyMCE image solution

Leave a Reply




You may use the tags listed below in your comments:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Published in
Tagged under
Some other categories