Input field character limitation using CoffeeScript
Based on the live textarea counter from spyrestudios.
http://spyrestudios.com/building-a-live-textarea-character-count-limit-with-css3-and-jquery/
<p>
<p>
<input class="field" type="text" />
<span class="counter">
<span>0</span>
Characters
</span>
</p>
<script class="cssdeck" src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
p {
p {
position: relative;
margin: 60px auto;
width: 60%;
}
.field {
padding: 4px 10px;
width: 100%;
height: 30px;
outline: 0;
border: 1px solid whitesmoke;
line-height: 30px;
&:focus {
outline: 0;
border-color: grey;
}
}
.counter {
position: absolute;
right: 0px;
bottom: 10px;
z-index: 20;
font-size: 12px;
span {
color: green;
&.warning {
color: red;
font-style: italic;
font-size: 14px;
}
}
}
$ () -> new characterCounter('.field', '.counter', 40)
$ () -> new characterCounter('.field', '.counter', 40)
class characterCounter
constructor: (field, counter, limit) ->
@$number = $(counter + ' > span')
@$input = $(field)
@$input.keyup( (e) =>
e.preventDefault()
@_count( @$input, limit )
)
_count: (input, limit) =>
value = $(input).val()
length = value.length
# check if the current length is over the limit
if length > limit
$(input).val( value.substr(0, limit) )
@$number.html(length - 1)
else
@$number.html(length)
# check if user has less than 20 chars left
if (limit - length) <= 20
@$number.addClass('warning')