text limiter (hard limit)

by John Allan

HTML

<div id="editor" contenteditable="true"></div>

CSS

#editor{
    width:400px;
    min-height:100px;
    border:1px solid black;
    padding:10px;
}

JavaScript

// JavaScript Document
// Dependencies: jquery
(function($) {

    $.fn.hcfRTEInputLengthLimiter = function(options) {

        var opts = $.extend({}, $.fn.hcfRTEInputLengthLimiter.defaults, options);

        return this.each(function() {
            var $this = $(this),
                o = $.meta ? $.extend({}, opts, $this.data()) : opts;

            hcfRTEInputLengthLimiter($this, o);
        });
    };

    function hcfRTEInputLengthLimiter($obj, opts) {

        var $el, $messageContainer;

        var saveSelection = function() {
            if (document.body.createTextRange) { //ms
                var s, p;
                s = document.selection.createRange();
                s.moveStart('character', -$el[0].childNodes[0].length);
                p = s.text.length;
                return p;
            } else if (window.getSelection) { //other
                var sel = window.getSelection(),
                    ranges = [];
                if (sel.rangeCount) {
                    for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                        ranges.push(sel.getRangeAt(i));
                    }
                }
                return ranges;
            }
        };

        var restoreSelection = function(savedSelection) {
            if (document.body.createTextRange) { //ms
                if (savedSelection) {
                    var textparent, s;
                    textparent = $el[0];
                    textparent.focus();
                    s = document.selection.createRange();
                    s.moveToElementText(textparent);
                    
                    s.moveStart('character', (savedSelection > opts.maxLength) ? opts.maxLength : savedSelection);
                    s.collapse(textparent, 0);
                    s.select();
                }
            } else if (window.getSelection) { //other
                var sel = window.getSelection();
                sel.removeAllRanges();
                for (var i =...