Toggle TinyMCE rich text editor effectively

Using TinyMCE effectively can take a bit of practice and time. Especially if you have multiple TinyMCE instances on the same page pulling dynamic data. Two common problems are to display the data itself and the other is to toggle the rich text editor on a TinyMCE enabled textarea to display rich text or not on the click of a button.

The first case can be tackled by pulling data after a small delay so that TinyMCE assets are loaded. The second case can be handled as follows:

To remove rich text capability from a textarea with the id ‘tmce-id’:

tinymce.get("tmce-id").save();
tinymce.execCommand('mceRemoveControl', true, "tmce-id");

In the above code, we saved the contents before removing the control so that the most recent edited text is available in plain view. You may also want to strip the tags that the editor had added to the text. You can just use a regular expression to do so and put in a function so you can reuse it quickly:

function stripHtml(str){
return str.replace(/<\S[^><]*>/gi, "");
}

So now the code would look like:

tinymce.get("tmce-id").save();
tinymce.execCommand('mceRemoveControl', true, "tmce-id");
var str = $("#tmce-id").val();
$("#tmce-id").val(stripHtml(str));

To add rich text again,

tinymce.execCommand('mceAddControl', true, "tmce-id");

In case of multiple TinyMCE textarea instances on the same page, you can pass a custom HTML attribute to the buttons that toggle TinyMCE. So if you are looping from 0 to 10 while adding textareas then the buttons that you are drawing for toggling can have a custom html attribute such as

<a class='enable-rte-btn' ref='tmce-id-0'>Enable Rich Text</a>
<a class='disable-rte-btn' ref='tmce-id-0'>Remove Rich Text</a>
<textarea id='tmce-id-0' class='tinymce'></textarea>

You can draw out multiple textareas like this incrementing 0 to 10 or whatever the number and then enable TinyMCE on textareas with the class ‘tinymce’. If there are too many textareas then pull the data after a small delay (based on the number of textareas you have) and load it in the textareas. After that add a click function to enable or disable rich text on all tags with the class ‘enable-rte-btn’ and ‘disable-rte-btn’ respectively.

Categories: Tips | Leave a comment

Leave a Reply

Required fields are marked *

*