2011-12-19 16:36:05 +00:00
|
|
|
###
|
|
|
|
# jCounter - a simple character counter
|
|
|
|
#
|
|
|
|
# @author Maximilian Mader
|
|
|
|
# @copyright 2011 Maximilian Mader
|
|
|
|
# @license Creative Commons Attribution-NonCommercial-ShareAlike <http://creativecommons.org/licenses/by-nc-sa/3.0/legalcode>
|
|
|
|
# @package jQuery.jCounter
|
|
|
|
###
|
|
|
|
(($) ->
|
2011-12-20 15:06:48 +00:00
|
|
|
$.fn.jCounter = (container, options) ->
|
2011-12-19 16:36:05 +00:00
|
|
|
options = $.extend
|
2011-12-20 15:06:48 +00:00
|
|
|
max: 0
|
2012-03-11 14:07:28 +00:00
|
|
|
counterClass: 'jCounter'
|
2011-12-19 16:36:05 +00:00
|
|
|
countUp: false
|
2012-03-11 14:07:28 +00:00
|
|
|
width: '100%'
|
2011-12-19 16:36:05 +00:00
|
|
|
, options
|
|
|
|
|
2012-09-23 15:37:18 +00:00
|
|
|
if @.attr('maxlength')
|
|
|
|
max = @.attr('maxlength')
|
2011-12-20 15:06:48 +00:00
|
|
|
else max = options.max
|
2012-03-11 14:07:28 +00:00
|
|
|
|
2011-12-20 15:06:48 +00:00
|
|
|
if !container
|
2012-09-23 15:37:18 +00:00
|
|
|
if !@.hasClass('jCounterInput')
|
|
|
|
@.addClass('jCounterInput')
|
|
|
|
@.wrap('<div class="jCounterContainer" style="width: ' + options.width + '"><div></div></div>').parent().append('<div class="' + options.counterClass + ' color-1">' + max + '</div>');
|
|
|
|
jCounterContainer = $(@).parent().children('.' + options.counterClass)
|
2011-12-20 15:06:48 +00:00
|
|
|
else
|
2011-12-27 10:51:43 +00:00
|
|
|
if typeof container is 'object'
|
2011-12-20 15:06:48 +00:00
|
|
|
jCounterContainer = container
|
|
|
|
else
|
|
|
|
jCounterContainer = $ container
|
2012-09-23 15:37:18 +00:00
|
|
|
|
|
|
|
@.on 'keypress keyup', $.proxy () ->
|
2011-12-19 16:36:05 +00:00
|
|
|
if options.countUp
|
2012-09-23 15:37:18 +00:00
|
|
|
length = @.val().length
|
2011-12-19 16:36:05 +00:00
|
|
|
else
|
2012-09-23 15:37:18 +00:00
|
|
|
length = max - @.val().length
|
2011-12-19 16:36:05 +00:00
|
|
|
|
2012-03-11 14:07:28 +00:00
|
|
|
if options.countUp && max > 0
|
|
|
|
if length < max / 2
|
|
|
|
color = 1
|
|
|
|
else if length >= max / 2 and length <= max / 1.2
|
|
|
|
color = 2
|
|
|
|
else
|
|
|
|
color = 3
|
|
|
|
else if options.countUp
|
2011-12-19 16:36:05 +00:00
|
|
|
color = 1
|
|
|
|
else
|
2011-12-20 15:06:48 +00:00
|
|
|
if length > max / 2
|
2011-12-19 16:36:05 +00:00
|
|
|
color = 1
|
2011-12-20 15:06:48 +00:00
|
|
|
else if length <= max / 2 and length >= max / 6
|
2011-12-19 16:36:05 +00:00
|
|
|
color = 2
|
|
|
|
else
|
|
|
|
color = 3
|
|
|
|
|
|
|
|
jCounterContainer.text(length).attr('class', '').addClass(options.counterClass + ' color-'+color)
|
2012-09-23 15:37:18 +00:00
|
|
|
, @
|
2011-12-19 16:36:05 +00:00
|
|
|
)(jQuery)
|