Justin808
Justin808

Reputation: 21512

How do I remove tinyMCE and then re-add it?

I am trying to add the tinyMCE editor to my page, remove it, then add it again but am getting errors.

When I run Part A, then Part B, Than Part A again I get the error:

Error: g.win.document is null
Source File: tiny_mce/tiny_mce.js Line: 1

Part A

tinyMCE.init({
    'mode' : 'exact',
    'elements' : '" + ctrl.ID + "Editor',
    'plugins' : 'insertdatetime,TVCMSLink,TVCMSImage',
    'theme' : 'advanced',
    'theme_advanced_layout_manager' : 'SimpleLayout',
    'theme_advanced_buttons1' : 'backcolor, forecolor, |, bold, underline, strikethrough, |, numlist, bullist, charmap, |, undo, redo, |, anchor, link, tvlink, unlink',
    'theme_advanced_buttons2' : '',
    'theme_advanced_buttons3' : ''
});

Part B

tinyMCE.getInstanceById('" + ctrl.ID + "Editor').remove();

Edit:

Below is the full JavaScript function. The first time through it opens the dialog and works, the contents is in the editor and there is no error. When I click the close button, the dialog is closed. When I run the function again, the dialog displays but the editor is empty and there is the above error.

function show_HP1B0() {
$('.EditLink').hide();
$.ajax({
    type: 'post',
    url: 'genericHandler.ashx',
    data: 'cmd=select&tableName=ExtraBlocks&id=4',
    dataType: 'json',
    success: function(data) {
        $('#HP1B0Editor').html(data['rows'][0]['Content']);
        alert($('#HP1B0Editor').html());
        tinyMCE.init({                 'mode' : 'exact', 
            'elements' : 'HP1B0Editor', 
            'plugins' : 'insertdatetime,Link,Image',
            'theme' : 'advanced',
            'theme_advanced_layout_manager' : 'SimpleLayout',
            'theme_advanced_buttons1' : 'backcolor, forecolor, |, bold, underline, strikethrough, |, numlist, bullist, charmap, |, undo, redo, |, anchor, link, tvlink, unlink',
            'theme_advanced_buttons2' : '',
            'theme_advanced_buttons3' : ''
        });
        var dlg = $('#ctl00_EXTRA_HTML_0_HP1B0Editor').dialog({
            modal: false,
            draggable: false,
            position: 'center',
            zIndex: 99999,  // Above the overlay
            width: 370,
            title: 'Content Block Editor',
            closeText: '',
            open: function () {
                $('body').css('overflow', 'hidden');
                if ($.browser.msie) { $('html').css('overflow', 'hidden'); } $('<div>').attr('id', 'loader').appendTo('body').show();
            },
            close: function () { $('body').css('overflow', 'auto'); if ($.browser.msie) { $('html').css('overflow', 'auto'); } $('#loader').remove(); },
            buttons: {
                'Save': function () {
                    tinyMCE.getInstanceById('HP1B0Editor').remove();
                    $('.EditLink').show();
                    $(this).dialog('close');
                },
                'Cancel': function () {
        alert('HP1B0Editor');
                    tinyMCE.getInstanceById('HP1B0Editor').remove();
                    $('.EditLink').show();
                    $(this).dialog('close');
                }
            }
        }).parent();
        dlg.appendTo(jQuery('form:first'));
    },
    error: function(data) {
        $('.EditLink').show();
        $('#HP1B0Editor').html('Error');
    }
});
}

Upvotes: 39

Views: 82156

Answers (14)

Eric
Eric

Reputation: 10626

Late to the party but it might save someone the headache. Here's what worked for me on version 4.2.4 (2015-08-17):

tinymce.EditorManager.editors = []; 

Then I could re-init an editor on the same dynamically created div

tinymce.init({selector:"#text"});   

Edit : 2020-06-20

With version: 5.2.x, do

 tinymce.activeEditor.destroy();
 

or

 tinymce.remove('#myeditor');

Upvotes: 45

nthaih
nthaih

Reputation: 71

Try this:

    var default_value_1 = 'test';
    var default_value_2 = 'test';

    tinyMCE.remove();

    tinyMCE.init({
        selector: '#id_element_1',
        plugins: 'print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template codesample table charmap hr pagebreak nonbreaking anchor toc insertdatetime advlist lists textcolor wordcount imagetools contextmenu colorpicker textpattern help code',
        toolbar: "code formatselect | bold italic strikethrough forecolor backcolor | link | alignleft aligncenter alignright alignjustify  | numlist bullist outdent indent  | removeformat"
    }).then(function(editors){
        editors[0].setContent(default_value_1 || '');
    });

    tinyMCE.init({
        selector: '#id_element_2',
        plugins: 'print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template codesample table charmap hr pagebreak nonbreaking anchor toc insertdatetime advlist lists textcolor wordcount imagetools contextmenu colorpicker textpattern help code',
        toolbar: "code formatselect | bold italic strikethrough forecolor backcolor | link | alignleft aligncenter alignright alignjustify  | numlist bullist outdent indent  | removeformat"
    }).then(function(editors){
        editors[0].setContent(default_value_2 || '');
    });

Upvotes: 2

mehmet
mehmet

Reputation: 8144

// Remove all editors bound to divs
tinymce.remove('div');

// Remove all editors bound to textareas
tinymce.remove('textarea');

// Remove all editors
tinymce.remove();

// Remove specific instance by id
tinymce.remove('#id');

from the tinymce documentation

Upvotes: 4

Kamil Smrčka
Kamil Smrčka

Reputation: 81

Try this:

 tinymce.remove();

    setTimeout(function () {
    tinymce.init(
        {
        selector: 'textarea',
        menubar: false,
        height: "300",
        plugins: [
            'advlist autolink lists link image charmap print preview anchor textcolor ksfm',
            'searchreplace visualblocks code fullscreen',
            'insertdatetime media table contextmenu paste code help'
        ],
        toolbar: 'undo redo | fontselect fontsizeselect styleselect | alignleft aligncenter alignright alignjustify | bold italic underline strikethrough | link table | ksfm'
        }
        );

    }, 1);

Upvotes: 5

Bj&#248;rn Stenfeldt
Bj&#248;rn Stenfeldt

Reputation: 1602

In the beginning I used:

tinymce.execCommand('mceRemoveEditor', true, id);
tinymce.execCommand('mceAddEditor', true, id);

But those commands run asynchronous, so the add command would often fail. As a workaround, I would:

tinymce.execCommand('mceRemoveEditor', true, id);
setTimeout(function() {
    tinymce.execCommand('mceAddEditor', true, id);
}, 500);

But I hated this solution, because it appeared slower to the user and even so you couldn't be sure that 500 milliseconds was enough if the computer was slow.

Now I'm using:

tinymce.remove(id);
tinymce.init({
    selector: id
});

I'm not sure why this works, but it works and this code doesn't have any of the asynchronous issues that the old code I used had.

Try it here: https://jsfiddle.net/g0u059au/

Upvotes: 0

rioted
rioted

Reputation: 1092

In case you have more editors with different settings, this is the way to reastart them preserving settings.

tinymce.EditorManager.editors.forEach(function(editor) {
    // code injection
    var old_global_settings = tinymce.settings;
    tinymce.settings = editor.settings;
    tinymce.EditorManager.execCommand('mceRemoveEditor', false, editor.id);
    tinymce.EditorManager.execCommand('mceAddEditor', false, editor.id);
    tinymce.settings = old_global_settings;
});

Upvotes: 9

jberculo
jberculo

Reputation: 1113

It is now possible to just do

tinymce.remove("#id .class or tag");

Upvotes: 16

Abhay Maurya
Abhay Maurya

Reputation: 12277

To remove existing tinymce editor and add new needs clearance of tinymce.EditorManager.editors array. This solution works in both cases : 1. If you have only one editor and you want to remove and add it again. 2. If you have multiple editors and you want to remove some special editor and add it again.

console.log(tinymce.EditorManager.editors);

This will give you a view of the array and exact index of you desired editor which you want to remove. For example one sample output of above console can be:

Array[2]
0:B
1:B
length:2
textarea-1:B
textarea-2:B
_proto_Array[0]

This is the output of the console when i have two tinymce editors on textareas : #textarea-1 and #textarea-2 Lets suppose I want to delete #textarea-2 and re-add it then it can be done as follows:

tinymce.EditorManager.editors.splice(1, 1);//removing second element in array.
delete tinymce.EditorManager.editors['textarea-2'];//deleting respective textarea id from array

Then you can add it again simply using init:

tinymce.init({
    selector:'#ts-textarea-2'
});

If you have only one textarea associated with tinymce editor lets say : #textarea-1 and you want to remove and re-initialize it then you can just empty tinymce.EditorManager.editors by :

tinymce.EditorManager.editors = [];

And then you can add using init command as explained above. Worked for me without any error.

I hope it helps

Upvotes: 1

azerafati
azerafati

Reputation: 18583

Just update it !

if you are looking at this to reset the content of the editor, instead of destroying it and initializing it again you can simply change the content like this

var editor = tinymce.get('editor_id'); //the id of your textarea
editor.setContent(content);  //any html as string

Upvotes: 1

Thariama
Thariama

Reputation: 50832

To cleanly remove an editor instance and avoid any errors use:

tinymce.EditorManager.execCommand('mceRemoveControl',true, editor_id);

To reinitialize the instance use:

tinymce.EditorManager.execCommand('mceAddControl',true, editor_id);

Be aware that when moving TinyMCE editors in the DOM you need to removeControl and addControl too, otherwise it results in JS errors.


As of TinyMCE 4 the methods to remove and reinitialize an instance are now...

To cleanly remove an editor instance and avoid any errors use:

tinymce.EditorManager.execCommand('mceRemoveEditor',true, editor_id);

To reinitialize the instance use:

tinymce.EditorManager.execCommand('mceAddEditor',true, editor_id);

Upvotes: 81

John Naegle
John Naegle

Reputation: 8247

For what its worth, I ended up doing this:

  1. Try to remove the editor right before I add it to the page (this worked for chrome)
  2. Before I remove the editor, trigger a save. This was important for firefox for some reason.

Here is what it looked like to add the editor:

  $(function() {
    tinymce.EditorManager.execCommand('mceRemoveEditor',true, 'fred');
    #{tinymce_javascript(:simple_editor, {height: 150, :selector => 'fred'})}
  });

  $(document).on('click', '.tinyMCE-save', function(event) {
    tinyMCE.triggerSave();
    return true;
  });

I had an explict click that removed the editor:

<a href="#" class="tinyMCE-save cool-js-click-handler">Cancel</a>

Upvotes: 0

Alexander
Alexander

Reputation: 1

All the above solutions didn't work for me ... This worked fine in my popup close event

var editor = tinyMCE.get('txtMailingText');
if (editor!=null) {
    editor.destroy();
}

Upvotes: 0

dageddy
dageddy

Reputation: 161

This works for me:

if (typeof(tinyMCE) != "undefined") {
  if (tinyMCE.activeEditor == null || tinyMCE.activeEditor.isHidden() != false) {
    tinyMCE.editors=[]; // remove any existing references
  }
}

Upvotes: 16

Rakesh
Rakesh

Reputation: 1366

Ok. just a word of caution.

If you have, say.. total of 5 textareas where you want to add/ remove tinymce instances.

AND

you want to do this more than once on a given page, Then its better to look for an alternative solution for your requirement.

Why?.. because even though everything would work fine, all the detaching and re-attaching of tinymce is going to take much time to execute. The browser will offer to stop the script for you etc.

source : my own experience where i tried keeping different textareas in separate hidden divs, and show it to the user when required.

Upvotes: 5

Related Questions