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.