Sunday, January 12, 2014

Character Count

Character Count

Character count for textarea with alert and cut-off. Based on experiment by Jason Saba.



<div class="wrapper">
  <h1>Textarea Character Count</h1>
  <textarea name="the-textarea" id="the-textarea" maxlength="140" placeholder="Enter Your Text Here"></textarea>
  <div id="the-count">
    <span id="current">0</span>
    <span id="maximum">/ 140</span>
  </div>
</div>

<script class="cssdeck" src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>

@import url(http://fonts.googleapis.com/css?family=Open+Sans:300,400,700,300italic);

*, *:before, *:after { box-sizing: border-box; }
html { font-size: 100%;  }
body { 
  font-family: 'Open Sans', sans-serif;
  font-size: 16px;
  background: tomato;
  color: #fff;
}

.wrapper {
  max-width: 65%;
  margin: auto;
}


h1 { 
  color: #fff; 
  margin: 3rem 0 1rem 0; 
  padding: 0;
  font-size: 1.5rem;
  font-family: 'Open Sans', sans-serif;
  font-weight: 400;
  display: block;
  text-align: Center;
}

textarea {
  width: 100%;
  min-height: 100px;
  resize: none;
  border: 1px solid #ddd;
  outline: none;
  padding: 0.5rem;
  color: #666;
  box-shadow: inset 0 0 0.25rem #ddd;
  &:focus {
    outline: none;
    border: 1px solid darken(#ddd, 5%);
    box-shadow: inset 0 0 0.5rem darken(#ddd, 5%);
  }
  &[placeholder] { 
    font-style: italic;
    font-size: 0.875rem;
  }
}

#the-count {
  float: right;
  padding: 0.1rem 0 0 0;
  font-size: 0.875rem;
}

$('textarea').keyup(function() {
    
  var characterCount = $(this).val().length,
      current = $('#current'),
      maximum = $('#maximum'),
      theCount = $('#the-count');
    
  current.text(characterCount);

  
  /*This isn't entirely necessary, just playin around*/
  if (characterCount < 70) {
    current.css('color', '#fff');
    current.css('font-weight', 'normal');
  }
  if (characterCount > 70 && characterCount < 90) {
    current.css('color', '#eee');
    current.css('font-weight', 'normal');
  }
  if (characterCount > 90 && characterCount < 100) {
    current.css('color', '#793535');
    current.css('font-weight', 'normal');
  }
  if (characterCount > 100 && characterCount < 120) {
    current.css('color', '#841c1c');
    current.css('font-weight', 'normal');
  }
  if (characterCount > 120 && characterCount < 139) {
    current.css('color', '#8f0001');
    current.css('font-weight', 'bold');
  }
  
  if (characterCount == 140) {
    maximum.css('color', '#8f0001');
    current.css('color', '#8f0001');
    theCount.css('font-weight','bold');
  } else {
    maximum.css('color','#fff');
    theCount.css('font-weight','normal');
  }
  
      
});