Using Garlic.js with TinyMCE WYSIWYG editor

Garlic.js is a great library – it uses localStorage to save the state of forms, so if your users accidentally close the tab or browser before submitting, their entry isn’t lost. This works seemlessly for almost all form elements, however WYSIWYG editors like TinyMCE present problems. Luckily it isn’t hard to fix – there’s a comment on the github repository for the project with the snippet you need to add to the init function:

setup : function(editor) {
    editor.on("change keyup", function(e){
        //tinyMCE.triggerSave(); // updates all instances; // updates this instance's textarea
        $(editor.getElement()).trigger('change'); // for garlic to detect change

So far so easy. But today the challenge was a little harder as WordPress was in the mix too.

At Helpful Technology we have a training product called Crisis90 that allows users work through a scenario and compare their responses. It is built on WordPress and makes use of GravityForms to allow users to submit responses to the crisis scenarios presented (there’s also a simulated Twitter environment for practicing real-time responses). When asking users to draft a press release, for example, we provide a WYSIWYG editor – this is native to GravityForms which in turn leverages the bundled TinyMCE library in WordPress. But this means that TinyMCE is being loaded automatically without me being able to modify the init function. Luckily there is a filter for that – tiny_mce_before_init. This filter lets you modify the settings array used to initialise TinyMCE. Despite the lack of a setup item in the defaults or example, it is perfectly valid. You can use this filter in a simple plugin or in your theme’s functions.php:

As you can see, we’re just adding a setup key to the $settings array containing the snippet from above. I’ve also included a little check that we aren’t in the admin area as I only want this to apply to the instances of TinyMCE used in forms on the front-end of the site.
Now Garlic.js will function correctly with TinyMCE, and a slip of the finger won’t lead to any lost work.



Leave a Reply

Your email address will not be published. Required fields are marked *