wp_editor disable after reaching character count limit

I want to disable input into an instance of wp_editor on the front end. This accurately tracks the number of characters, but allows input after the limit is reached.

function my_char_count( $initArray ) {

  if ( ! is_admin() ) {   

    $initArray['setup'] = <<<JS
[function(ed) {
    ed.on('keyup', function(e) {

        var content = ed.getContent().replace(/(<[a-zA-Z\/][^<>]*>|\[([^\]]+)\])|(\s+)/ig,''); 
        var max = 20;
        var len = content.length;

        var diff = max - len; 
        if ( diff < 1 ) {
            // none of these prevents input
            ed.stopPropagation();
            ed.preventDefault();
            tinymce.dom.Event.cancel(e);
            return false;

        }    
        document.getElementById("character_count").innerHTML = "Characters Left: " + diff;    

    });

}][0]
JS;
  }

    return $initArray;
}
add_filter( 'tiny_mce_before_init', 'my_char_count' );

1
1

I guess the keyup event is too late.

If you use the keypress event instead of keyup, then this seems to work:

ed.on( 'keypress', function(e) {
    var content = ed.getContent().replace(
        /(<[a-zA-Z\/][^<>]*>|\[([^\]]+)\])|(\s+)/ig, '' );
    var max = 20;
    var len = content.length;
    var diff = max - len;       

    if ( diff < 1 )
        tinymce.dom.Event.cancel(e);

    document.getElementById("character_count").innerHTML = "Characters Left: " + diff;
} );

The keypress event will not log keys like Alt, Enter, Control, ArrowUp, … so when the maximum allowed content length is reached, we won’t get stuck!

This should also work for the keydown, but it logs all keys, so we would then we have to add exceptions for the allowed keys.

Leave a Comment