1
votes

I have added a custom plugin to CKEditor inline to perform bold operation. The plugin is working as expected but the on/off state of button is not working.

When command is executed its state is always TRISTATE_OFF.

CKEDITOR.plugins.add( 'customBold', {
    requires: 'toolbar',
    icons: 'bold',
    hidpi: false, 
    init: function( editor ) {


        var boldCommand = {
            exec: function( editor ) {  
                document.execCommand('bold', false, null);              
            }
        }

        editor.addCommand( 'bold', boldCommand );   

        editor.ui.addButton && editor.ui.addButton( 'Bold', {
                label:  'bold',
                command: 'bold',
                toolbar: 'basic,10'
        });    

       editor.setKeystroke( [
            [ CKEDITOR.CTRL + 66 /*B*/, 'bold' ]                
       ]);
    }
});

When user selects the bold text I would like to toggle the bold style in toolbar.

2

2 Answers

4
votes

You need to call the command.setState method which will set the state of the command which then automatically affects the state of related button.

However, you need to know when to call that method (when the state changes). CKEditor's plugins like the basicstyle plugin use the CKEditor's styles system which let them easily listen on style state changes:

editor.attachStyleStateChange( style, function( state ) {
    !editor.readOnly && editor.getCommand( commandName ).setState( state );
} );

You, however, try to use the native commands, which I highly recommend not to. It is not a coincidence that CKEditor implements its own style system and its own commands.

0
votes

I'm answering this purely because this result constantly came up when I was looking how to apply a style to a CKEditor custom plugin button on the toolbar.

This ended up being fairly simple, although not especially elegant.

Currently, I do my own handling of CKEditor buttons (outside of the plugin.js files). This is because I'm using CKEditor to dynamically create editor instances, which it doesn't seem very well suited to do and I often have to override functions.

Here's how I apply a style to a 'active' button in the editor on the myplugin button action:

//Catch the initial click
$('.parent_element').on('click', '.cke_button__myplugin', function(){ 
    //Apply a gradiant style to the button
    $('.cke_button__myplugin').css({'background':' radial-gradient(#FFF, #6E6E6E)'})
    //Logic to handle button click 

});

This way, you simply apply a style to the button without having to toggle the actual button.png