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" data-maxlength="255" data-countdown="true">
<span class="counter hide"></span>
CSS
body {
font: normal 62.5%/1 Helvetica, Arial, sans-serif;
padding: 10px;
}
h1 {
font-size: 200%;
line-height: 1.5;
}
.hide { display: none; }
.counter {
-webkit-transition: all .25s;
-moz-transition: all .25s;
-o-transition: all .25s;
transition: all .25s;
}
.counter {
padding: 2px 4px;
/* -- Green -- */
color: #468847;
background-color: #dff0d8;
border: 1px solid #d6e9c6;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
.almost {
/* -- Blue -- */
color: #3a87ad;
background-color: #d9edf7;
border-color: #bce8f1;
}
.warn {
/* -- Yellow -- */
color: #c09853;
background-color: #fcf8e3;
border-color: #fbeed5;
}
.whoa {
/* -- Red -- */
color: #b94a48;
background-color: #f2dede;
border-color: #eed3d7;
}
.ludicrous {
/* -- Red -- */
color: #fff;
background-color: #b94a48;
border-color: #b94a48;
}
JavaScript
/*
Original: http://jsfiddle.net/ritcheyer/KuN8u/
Forked by @niccai: http://jsfiddle.net/niccai/D76CV/
Forked again by @ritcheyer
Changes:
- combined all vars
- reordered vars so maxlength can be set by data attrib of input field
*/
function updateCountdown(input) {
var $input = input,
$countDisplay = $input.next(),
inputMax = $input.data('maxlength'),
counter = $input.val().length,
classSet = 'warn whoa ludicrous almost';
counter = inputMax - counter;
if (counter > 20) {
// normal
$countDisplay.removeClass(classSet);
} else {
if (counter < 10) {
if (counter < 5) {
if (counter < 0) {
// ludicrous
$countDisplay.removeClass(classSet).addClass('ludicrous');
} else {
// whoa
$countDisplay.removeClass(classSet).addClass('whoa');
}
} else {
// warn
$countDisplay.removeClass(classSet).addClass('warn');
}
} else {
// almost
$countDisplay.removeClass(classSet).addClass('almost');
}
}
$countDisplay.text(counter);
}
$('document').ready(function() {
$('input[type=text]').focus(function() {
if ($(this).data('countdown')) {
updateCountdown($(this));
$(this).next('span').fadeIn(250);
}
}).change(function() {
updateCountdown($(this))
}).keyup(function() {
updateCountdown($(this))
});
});