Search code examples
javascripttinymcetextarea

Return text-area Editor length on keyup tinymce


This is my JS.

<script>
tinymce.init({
    selector: 'textarea.editor',
    ...
    toolbar: true,
    init_instance_callback: function(editor) {
        editor.on('keyUp', function(e) {
            var text = tinymce.get(e).text().length;
            if( text == 0  ) {
                $(body).removeClass('active-text');
            } else {
                $(body).addClass('active-text');
            }
        });
    },
    setup: function (editor) {
    ...
    }
});
</script>

This code doesn't work for TinyMCE.

The following error console is displayed:

Error: Uncaught TypeError: tinymce.get(...) is null

Solution

  • Your code is not using the TinyMCE API correctly. The get() API is looking for the id of the textarea that was replaced by TinyMCE.

    https://www.tiny.cloud/docs/tinymce/6/apis/tinymce.root/#get

    As you are not passing the string of an id that won't work. The code you have already has a reference to the TinyMCE editor via the editor variable so you can just do something like:

    editor.getContent({format: 'text'}).length