Dynamically Add and remove TinyMCE editor with jQuery

TinyMCE converts HTML textarea or any other HTML element to WYSIWYG editor. Where you can directly preview the changes.

Sometimes require toggling TinyMCE instance from the HTML element.

Generated HTML from TinyMCE editor will display on HTML element when an instance is removed.

In this tutorial, I show how you can dynamically add remove TinyMCE editor from HTML element with jQuery.

Dynamically Add and remove TinyMCE editor with jQuery


Contents

  1. Download and Include
  2. HTML
  3. jQuery
  4. Demo
  5. Conclusion

 


1. Download and Include

  • Download TinyMCE and include tinymce.min.js with jQuery library in the <head> section.
<script src='tinymce/js/tinymce/tinymce.min.js' type='text/javascript'></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

2. HTML

Create a button for toggle Editor and a <textarea id='editor'>.

Completed Code

<input type='button' value='Toggle Editor' id='but_toggle'>
<div>
  <textarea id='editor' style='width: 99%; height: 200px;'></textarea>
</div>

3. jQuery

I created a user-defined function addTinyMCE() where initialize TinyMCE on <textarea id='editor'> element.

Call the addTinyMCE() function on document ready.

Toggle

On Toggle Editor button click first check whether TinyMCE is initialized or not.

If initialized then remove it using tinymce.remove('#editor') where pass the textarea id otherwise call addTinyMCE() function.

NOTE – If you want to remove from textarea instead by id then call tinymce.remove('textarea');. Or if you want to remove all TinyMCE editor on the page then call tinymce.remove().

Completed Code

$(document).ready(function(){

  // Add TinyMCE
  addTinyMCE();

  // Toggle Editor
  $('#but_toggle').click(function(){

   // Check TinyMCE initialized or not
   if(tinyMCE.get('editor')){

     // Remove instance by id
     tinymce.remove('#editor');
   }else{

     // Add TinyMCE
     addTinyMCE();
   }
 
  });
});

// Add TinyMCE
function addTinyMCE(){
  // Initialize
  tinymce.init({
    selector: '#editor',
    themes: 'modern',
    height: 200
  });
}

4. Demo

Click on the Toggle Editor button.


5. Conclusion

Use tinymce.remove() method to remove TinyMCE editor from the HTML element and again call tinymce.init() on the selector to reinitialize.

If you find this tutorial helpful then don’t forget to share.