javascripttinymcetinymce-4tinymce-3

toggleClass function in TinyMCE API 3?


TinyMCE 4 has a handy toggleClass function, http://archive.tinymce.com/wiki.php/api4:method.tinymce.dom.DOMUtils.toggleClass which I'd like to use, but this particular project icorporates the older TinyMCE 3.5.11 ..

I'd hoped that the following would work in v3:

tinymce.create('tinymce.plugins.ClassToggle', {
    createControl: function(n, cm) {
        switch (n) {
            case 'exampleclasstoggle':
                var exampleclasstoggle = cm.createButton('exampleclasstoggle', {
                    title : 'Toggle example class',
                    image : '/admin/js/icons/exampleclass.png',
                    onclick : function(v) {
                        cm.editor.selection.toggleClass('example');
                    }
                });

                return exampleclasstoggle;
        }
    }
});

tinymce.PluginManager.add('classtoggle', tinymce.plugins.ClassToggle);

But it's just throwing errors that toggleClass() isn't a function so clearly the v3 API just doesn't offer this.

Does anybody know of a plugin for TinyMCE 3 that provides a toggleClass() or similar, or is there a better way of doing this?

I literally just want to add buttons to the editor for toggling a couple of pre-defined classes on whatever element is selected.

Regards.


Solution

  • Managed to do it using the tinymce.dom API to access hasClass, addClass and removeClass functions...

    tinymce.create('tinymce.plugins.ClassToggle', {
        createControl: function(n, cm) {
            switch (n) {
                case 'exampleclasstoggle':
                    var exampleclasstoggle = cm.createButton('exampleclasstoggle', {
                        title : 'Toggle example class',
                        image : '/admin/js/icons/exampleclass.png',
                        onclick : function(v) {
                            if(cm.editor.dom.hasClass(cm.editor.selection.getNode(), 'example')) {
                                cm.editor.dom.removeClass(cm.editor.selection.getNode(), 'example');
                            } else {
                                cm.editor.dom.addClass(cm.editor.selection.getNode(), 'example');
                            }
                        }
                    });
    
                    return exampleclasstoggle;
            }
        }
    });
    
    tinymce.PluginManager.add('classtoggle', tinymce.plugins.ClassToggle);