Code Snippet: Prevent Flickering When Enforcing Maxlength on Textareas

I was doing some research today regarding how to limit the number of characters on the page while removing the annoying flickering effect that often occurs with JavaScript-based solutions to the problem. Here’s what I came up with:

document.addEventListener('DOMContentLoaded', function() {
        var textArea = document.getElementById('textarea'), // Just a random <textarea> on the page
            charRemainingLabel = document.getElementById('charsRemaining'); // span on the page to show chars left

        limitTextLength = function(e) {
            var maxLength = 200,
                charsRemaining = 200,
                me = this;

            e = e || window.event;
            key = e.which;
            charsRemaining = Math.max(0, (maxLength - me.value.length));

            charRemainingLabel.textContent = charsRemaining + " characters remaining";
            if( (key > 31 || key === 13) && e.type === 'keypress') {
                if(charsRemaining <= 0) { // cancel normal typing
            } else { // Allows for backspace and copy-and-paste
                me.value = me.value.substr(0, 200);

        textArea.addEventListener('keypress', limitTextLength, false);
        textArea.addEventListener('keyup', limitTextLength, false);
    }, false);

The most important part is the distinction between keypress and keyup. The keypress event can be canceled properly because it occurs whenever a regular key is pressed (letters, numbers, etc.,). However, if you want the event to fire when keys like backspace are hit, you need to add the same handler to the keyup event.