Dynamically Adding and Removing TinyMCE 3 Wysiwyg Editor

In this tutorial we will learn how to add and remove tinymce editor on HTML control.Tinymce is most popular and platform independent web-based JavaScript HTML WYSIWYG control.TinyMCE enables you to convert HTML textarea and div input fields or other HTML elements into WYSIWYG editor instances.

Tinymce will not work when you are loading and unloading textarea/div element using ajax.tinymce is not work again on control if you do not detach tinymce from HTML input control.So in this tutorial i will provide you simple JavaScript code to add and remove tinymce on textarea/div elements.

SImple Exmaple of Tinymce 3 Wysiwyg Editor

tinymce_result

Simple Steps to Instantiate TinyMCE Dynamically

Step 1: We will include tinymce library files in head section of index.html.

Select Code
1
2
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.1.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tinymce/3.5.8/tiny_mce.js"></script>

Step 2: We will create textarea control in index.html.

Select Code
1
<textarea class="tinymce-enabled-message" cols="80" id="description1">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam tincidunt est ac dolor condimentum vitae laoreet ante accumsan. Nullam tincidunt tincidunt ante tempus commodo.</textarea>

Step 3: Create function to apply tinymce on control.

Select Code
1
2
3
4
5
6
7
function applyMCE() {
    tinyMCE.init({
        mode : "textareas",
        theme : "simple",
        editor_selector : "tinymce-enabled-message"       
    });      
}

Step 3: Call above function at the end of DOM.

Select Code
1
applyMCE()

Step 4: Add tinymce editot on control.

Select Code
1
tinyMCE.execCommand('mceAddControl', false, 'description');

Step 5: Remove tinymce from control.

Select Code
1
2
tinyMCE.execCommand('mceFocus', false, editorId);                    
tinyMCE.execCommand('mceRemoveControl', false, editorId);

If you want to add tinymce based on control id then you need to call below script:

Select Code
1
2
3
4
5
6
var editorId = 'description'; 
//added tinymce
tinyMCE.execCommand('mceAddControl', false, editorId);
//remove tinymce
tinyMCE.execCommand('mceFocus', false, editorId);                    
tinyMCE.execCommand('mceRemoveControl', false, editorId);

Some times we dont know tinymce is applied or not, in this type situation you need to check instance is created, if created then first remove then add as like below script.

Select Code
1
2
3
4
5
6
var editorId = 'description';                   
                    if(tinyMCE.getInstanceById(editorId)) 
                    { 
                        tinyMCE.execCommand('mceFocus', false, editorId);                    
                        tinyMCE.execCommand('mceRemoveControl', false, editorId);
                    }

You can download source code and Demo from below link.