jQuery textarea character limiter

by gabrieleromanato

HTML

<textarea id="editor"></textarea>
<div id="counter"></div>

CSS

textarea {
    display: block;
    margin: 1em;
    width: 400px;
    height: 300px;
    border: 1px solid;
}

JavaScript

(function($) {
    $.fn.limiter = function(options) {

        var that = this;
        options = $.extend({
            limit: 100,
            counter: $('#counter')
        }, options);

        var count = function(value, e) {

            var total = options.limit - value.length;

            if (total >= 0) {
                options.counter.text(total);
            } else {

                if (e.type == 'keypress') {

                    e.preventDefault();


                }
            }


        };

        return that.each(function() {

            $(that).on('keypress keyup', function(evt) {

                count($(that).val(), evt);

            });

        });

    };
})(jQuery);

$('#editor').limiter();