Blame view

bower_components/Materialize/js/character_counter.js 1.56 KB
74249687   Luigi Serra   Cross browser con...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
  (function ($) {
  
    $.fn.characterCounter = function(){
      return this.each(function(){
  
        var itHasLengthAttribute = $(this).attr('length') !== undefined;
  
        if(itHasLengthAttribute){
          $(this).on('input', updateCounter);
          $(this).on('focus', updateCounter);
          $(this).on('blur', removeCounterElement);
  
          addCounterElement($(this));
        }
  
      });
    };
  
    function updateCounter(){
      var maxLength     = +$(this).attr('length'),
      actualLength      = +$(this).val().length,
      isValidLength     = actualLength <= maxLength;
  
      $(this).parent().find('span[class="character-counter"]')
                      .html( actualLength + '/' + maxLength);
  
      addInputStyle(isValidLength, $(this));
    }
  
    function addCounterElement($input){
      var $counterElement = $('<span/>')
                          .addClass('character-counter')
                          .css('float','right')
                          .css('font-size','12px')
                          .css('height', 1);
  
      $input.parent().append($counterElement);
    }
  
    function removeCounterElement(){
      $(this).parent().find('span[class="character-counter"]').html('');
    }
  
    function addInputStyle(isValidLength, $input){
      var inputHasInvalidClass = $input.hasClass('invalid');
      if (isValidLength && inputHasInvalidClass) {
        $input.removeClass('invalid');
      }
      else if(!isValidLength && !inputHasInvalidClass){
        $input.removeClass('valid');
        $input.addClass('invalid');
      }
    }
  
    $(document).ready(function(){
      $('input, textarea').characterCounter();
    });
  
  }( jQuery ));