Character Decrement
Creating a simple input field countdown. There's a bunch of optimizations to be made here, but this is at least a start. Code stored on bitbucket here: http://j.mp/JIDjeq Feel free to fork it!
by ritcheyer
HTML
<h1>Character Counter</h1>
<input type="text" maxlength="255" data-maxlength="255" data-countdown="true">
<span class="msg-counter" title="Number of Characters Left"></span>
CSS
/*
* Character Decrementing
* Author: Eric Ritchey
*/
.msg-counter {
min-width: 30px;
border: 1px solid inherit;
border-left: 0;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
-webkit-transition: all .25s;
-moz-transition: all .25s;
-o-transition: all .25s;
transition: all .25s;
}
/* -- Green -- */
.msg-focused {
color: #468847;
background-color: #dff0d8;
border-color: #468847;
}
/* -- Blue -- */
.msg-almost {
color: #3a87ad;
background-color: #d9edf7;
border-color: #3a87ad;
}
/* -- Yellow -- */
.msg-warn {
color: #bf9753;
background-color: #fcf8e3;
border-color: #c09853;
}
/* -- Red -- */
.msg-whoa {
color: #b94a48;
background-color: #f2dede;
border-color: #b94a48;
}
/* -- Red -- */
.msg-ludicrous {
z-index: 1;
position: relative;
color: #b94a48;
background-color: #f2dede;
border-color: #b94a48;
-webkit-box-shadow: 0 0 6px rgba(160,17,14,1);
-moz-box-shadow: 0 0 6px rgba(160,17,14,1);
box-shadow: 0 0 6px rgba(160,17,14,1);
}
JavaScript
/*
* Original: http://jsfiddle.net/ritcheyer/KuN8u/
* Forks:
* - @niccai: http://jsfiddle.net/niccai/D76CV/
* - @ritcheyer: http://jsfiddle.net/ritcheyer/sXc6R/
* - @ritcheyer: http://jsfiddle.net/ritcheyer/bYZkS/
*
* Changes:
* - renamed counter to be more OO (prepended everything with msg-)
*/
function updateCountdown(input) {
var $input = input,
$countDisplay = $input.next(),
inputMax = $input.data('maxlength'),
counter = $input.val().length,
cntNormal = 20,
clsNormal = 'msg-focused',
cntAlmost = 15,
clsAlmost = 'msg-almost',
cntWarn = 10,
clsWarn = 'msg-warn',
cntWhoa = 5,
clsWhoa = 'msg-whoa',
cntLudicrous = 0,
clsLudicrous = 'msg-ludicrous',
clsSet = clsNormal + ' ' + clsAlmost + ' ' + clsWarn + ' ' + clsWhoa + ' ' + clsLudicrous;
counter = inputMax - counter;
if (counter > cntNormal) {
// normal
$countDisplay.removeClass(clsSet);
} else {
if (counter <= cntAlmost) {
if (counter <= cntWarn) {
if (counter <= cntWhoa) {
if (counter == cntLudicrous) {
// ludicrous message
$countDisplay.removeClass(clsSet).addClass(clsLudicrous);
} else {
// whoa message
$countDisplay.removeClass(clsSet).addClass(clsWhoa);
}
} else {
// warn message
$countDisplay.removeClass(clsSet).addClass(clsWarn);
}
} else {
// almost message
$countDisplay.removeClass(clsSet).addClass(clsAlmost);
}
} else {
// green class
$countDisplay.removeClass(clsSet).addClass(clsNormal);
}
}
...