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!
HTML
<!-- migrated to codepen: https://codepen.io/ritcheyer/pen/ybgyPY -->
<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
function updateCountdown() {
var remaining = 40 - $('input[type=text]').val().length;
if (remaining > 20) {
$('.counter').removeClass('warn whoa ludicrous almost');
}
if (remaining < 20) {
$('.counter').removeClass('warn whoa ludicrous').addClass('almost');
}
if (remaining < 10) {
$('.counter').removeClass('almost whoa ludicrous').addClass('warn');
}
if (remaining < 5) {
$('.counter').removeClass('almost warn ludicrous').addClass('whoa');
}
if (remaining <= 0) {
$('.counter').removeClass('almost warn whoa').addClass('ludicrous');
}
$('.counter').text(remaining);
}
$('document').ready(function() {
$('input[type=text]').focus(function() {
if ($(this).data('countdown')) {
updateCountdown();
$(this).next('span').fadeIn(250);
}
});
$('input[type=text]').change(updateCountdown);
$('input[type=text]').keyup(updateCountdown);
});