input_reaction.js 1.49 KB

(function($, undefined) {

  var events = {
    'textarea': [
      'keyup',
      function (dom, opts) {
        var domCache = dom.find('.wordnumber');
        var max = opts.max;
        dom.find('.wordtotal').html(max);

        return function () {
          domCache.html(this.value.length);

          if (this.value.length + 30 > max) {
            dom.addClass('showhint');
          }else {
            dom.removeClass('showhint')
          };

          if (this.value.length >= max) {
            this.value = this.value.slice(0, max);
          };
        }
      }
    ]  
  };

  var tpl = {
    'textarea': '<div class="lnumber"><span class="wordnumber">0</span><span>/</span><span class="wordtotal">200</span></div>'
  };

  var doms = {
    'textarea': ''
  }

  var _input = function (selector, options) {
    if ($(selector).length) {
      this.selector = $(selector);
      this.opt = $.extend({
        'max': 200
      }, options)
      this.init();
    };
  };

  _input.prototype.init =
  function() {
    var word, cache;

    for (var i = 0, l = this.selector.length; i < l; i++) {
      cache = this.selector[i].nodeName.toLowerCase();
      doms[cache]  = $(tpl[cache]);

      $(this.selector[i]).parent().append(doms[cache]);
      $(this.selector[i]).on(events[cache][0], events[cache][1](doms[cache], this.opt));
    };
  };

  if (typeof define == 'function') {
    define(function () {
      return _input;
    });
  }else {
    window._input_reaction = _input;
  };
})($, undefined);