ckeditor set justifyblock at default in an instance without focusing

493 Views Asked by At

I have 4 ckeditor instances on one page and I want to set a style on the last one (justifybloc).

for now I use this code :

  CKEDITOR.on('instanceReady', function(evt) {

    if (evt.editor.name != undefined) {
      if (evt.editor.name.indexOf('edit-field-body-1') > -1) {
         evt.editor.execCommand( 'justifyblock' );
      }
    }
 });

execCommand focus my textarea and i don't want.

I don't know other method to do this.

Thank you.

2

There are 2 best solutions below

0
On BEST ANSWER

I solved my problem with this solution

CKEDITOR.on('instanceReady', function(evt) {
  if (evt.editor.name != undefined) {
    if (evt.editor.name.indexOf('edit-field-body-1') > -1) {
       evt.editor.on('focus', function() { 
         this.execCommand( 'justifyblock' ); 
       });
     }
   }
 }

Code pen exemple

1
On

The code you provided works as you said, focusing the editor. Additionally it will justify/align only first block element (e.g. paragraph) as the focus is set on the beginning of the editor. It is not possible to use this command without focusing editor.

However, to achieve justifying/aligning only first block element you can use a little hackish solution and set element style manually (in a way it is properly recognized by justify plugin):

CKEDITOR.on('instanceReady', function(evt) {

    if (evt.editor.name != undefined) {
        if (evt.editor.name.indexOf('editor1') > -1) {
            evt.editor.editable().getChild( 0 ).setStyle( 'text-align', 'justify' );
        }
    }
} );

See working codepen.

Such solution has some disadvantages (e.g. it assumes that the first element in the editor is block element - which is true in most cases, etc.), but should be sufficient for most cases.


By the way, if the fact that editor content gets selected does not bother you and you would like to justify/align whole content it has to be selected first (selectall plugin needed), like:

CKEDITOR.on('instanceReady', function(evt) {

    if ( evt.editor.name != undefined ) {
        if ( evt.editor.name.indexOf( 'editor1' ) > -1 ) {
            evt.editor.execCommand( 'selectAll' );
            evt.editor.execCommand( 'justifyblock' );
        }
    }
} );

Of course you may always move the selection/focus somewhere else later.