summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorbrandonaaron <brandon.aaron@gmail.com>2009-01-15 13:03:07 -0600
committerbrandonaaron <brandon.aaron@gmail.com>2009-01-15 13:03:07 -0600
commit9fc7eedbb6baf31e3f43031cde2a4d5f1e0767df (patch)
treea9b04f88126b5e0d3e04416688b680b12b0c6f81
parent853bb18f2b763a99d32e6c1ffcfb69020d0cc218 (diff)
downloadjquery-countable-9fc7eedbb6baf31e3f43031cde2a4d5f1e0767df.zip
jquery-countable-9fc7eedbb6baf31e3f43031cde2a4d5f1e0767df.tar.gz
jquery-countable-9fc7eedbb6baf31e3f43031cde2a4d5f1e0767df.tar.bz2
stop repeating the same check over and over again
-rw-r--r--jquery.countable.js16
1 files changed, 15 insertions, 1 deletions
diff --git a/jquery.countable.js b/jquery.countable.js
index b827a64..4ce47ac 100644
--- a/jquery.countable.js
+++ b/jquery.countable.js
@@ -8,7 +8,7 @@
$.fn.extend({
countable: function(options) {
return this.each(function() {
- var $this = $(this), interval, $el;
+ var $this = $(this), interval, prev_char_diff, $el;
options = $.extend({
threshold: 0.5,
appendMethod: 'insertAfter', // insertBefore || insertAfter
@@ -22,20 +22,30 @@ $.fn.extend({
negativeCopy: "You are {n} characters over.",
fadeDuration: 'normal'
}, options);
+
$el = $('<'+options.tagName+'/>')
.html( options.positiveCopy.replace("{n}", '<span class="num"/>') )
.addClass( options.className )
.css({ opacity: 0 });
$el[options.appendMethod]($this);
+
$this
.bind('keyup', check)
.bind('focus blur', function(event) {
if ( event.type == 'blur' ) clearInterval( interval );
if ( event.type == 'focus' && !interval ) setInterval(check, options.interval);
});
+
function check() {
var val = $this.val(), length = val.length, percentage_complete = length/options.maxLength, char_diff = options.maxLength - length;
+ if ( prev_char_diff != undefined && char_diff == prev_char_diff ) return;
opacity = options.startOpacity + ((options.threshold - percentage_complete) * ((options.startOpacity * 2) - 2));
+
+ if ( $el.is(':hidden') && percentage_complete >= options.threshold )
+ $el.show();
+ if ( $el.is(':visible') && percentage_complete < options.threshold )
+ $el.hide();
+
$el.stop().fadeTo( options.fadeDuration, percentage_complete >= options.threshold ? opacity : 0 );
if ( char_diff >= 0 ) {
if ( $el.is( '.'+options.maxClassName ) )
@@ -44,12 +54,16 @@ $.fn.extend({
if ( !$el.is( '.'+options.maxClassName ) )
$el.html( options.negativeCopy.replace("{n}", '<span class="num"/>') );
}
+
$el[ (char_diff < 0 ? 'add' : 'remove') + 'Class' ]( options.maxClassName );
$el.find('.num').text( Math.abs(char_diff) );
+
if ( char_diff == -1 || char_diff == 1 )
$el.html( $el.html().replace(/characters\b/, "character") );
else
$el.html( $el.html().replace(/character\b/, "characters") );
+
+ prev_char_diff = char_diff;
};
check();
});