4

I'd like to listen to the focus event in CKEditor 5.

I thought something like this would work but the callback is never called:

document.querySelector("#editable");
ClassicEditor.create(el).then(editor => {
    editor.on('focus', () => {
        console.log("Focused");
    });
});

The editor is successfully created but the callback is not called.

Any ideas?

Michael Bates
  • 1,884
  • 2
  • 29
  • 40

1 Answers1

10

The editor comes with a FocusTracker (and the observable #isFocused property) for that purpose:

editor.ui.focusTracker.on( 'change:isFocused', ( evt, name, value ) => {
    console.log( 'isFocused = ', value );
} );

Note that editor.ui.focusTracker.isFocused is true as long as any UI has focus, which includes the editable but also the toolbar, floating panels, etc.

To determine the focus of the editable, i.e. when the caret is blinking and typing is possible, use this listener instead:

editor.editing.view.document.on( 'change:isFocused', ( evt, name, value ) => {
    console.log( 'editable isFocused =', value );
} );

Place one listener next to the other and play with the editor and the UI to see the difference.

oleq
  • 15,697
  • 1
  • 38
  • 65
  • 2
    Psst! I just wanted to let you know there's an [official guide](https://ckeditor.com/docs/ckeditor5/latest/framework/guides/deep-dive/ui/focus-tracking.html) about focus tracking in CKEditor 5 you may want to check out. – oleq May 04 '20 at 15:20