Last active
August 29, 2015 13:56
-
-
Save bcole808/9194060 to your computer and use it in GitHub Desktop.
Character limit indicator for text input fields
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*************************************************** | |
* Character Limit Counter displays an indicator below a text field telling the user how many characters they have left. | |
* | |
* INSTRUCTIONS: | |
* Add the attribute maxlength="XX" to your text input. | |
* Add the class "characterLimitCounter" to your text input. | |
***************************************************/ | |
var characterLimitCounter = { | |
initialize : function() { | |
$(".characterLimitCounter").each(function() { | |
var limit = $(this).attr("maxlength") || 160; | |
characterLimitCounter.setupCounter($(this), limit); | |
}); | |
}, | |
setupCounter : function($elem, limit) { | |
// Create a DOM element to show the character count | |
var $counter = $('<p class="charactersRemaining"><span class="num">'+limit+'</span> characters remaining.</p>'); | |
var $counterNum = $counter.find('.num'); | |
// Set intital count | |
$counterNum.html(limit - $elem.val().length); | |
$elem.after($counter); | |
$elem.bind('keyup', function(){ | |
var charactersUsed = $elem.val().length; | |
if (charactersUsed > limit){ | |
charactersUsed = limit; | |
$elem.val($elem.val().substr(0, limit)); // Force text limit | |
} | |
var charactersRemaining = limit - charactersUsed; | |
$counterNum.html(charactersRemaining); | |
// Change color of indicator when running low on characters | |
if (charactersRemaining < 10) { | |
$counter.css('color','red'); | |
} else if(charactersRemaining < 25) { | |
$counter.css('color','#AA0000'); | |
} else { | |
$counter.css('color',''); | |
} | |
}); | |
} | |
} /* end characterLimitCounter */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment