Skip to content

Commit

Permalink
Merge pull request #2 from sosoHero/sosoHero-multi-character-counter
Browse files Browse the repository at this point in the history
Prevent Multiple Character Counters on Same Element
  • Loading branch information
sosohero committed Feb 21, 2016
2 parents 5dc7032 + ae57666 commit ef59c12
Showing 1 changed file with 20 additions and 9 deletions.
29 changes: 20 additions & 9 deletions js/character_counter.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,23 @@

$.fn.characterCounter = function(){
return this.each(function(){
var $input = $(this);
var $counterElement = $input.parent().find('span[class="character-counter"]');

var itHasLengthAttribute = $(this).attr('length') !== undefined;
// character counter has already been added appended to the parent container
if ($counterElement.length) {
return;
}

var itHasLengthAttribute = $input.attr('length') !== undefined;

if(itHasLengthAttribute){
$(this).on('input', updateCounter);
$(this).on('focus', updateCounter);
$(this).on('blur', removeCounterElement);
$input.on('input', updateCounter);
$input.on('focus', updateCounter);
$input.on('blur', removeCounterElement);

addCounterElement($(this));
addCounterElement($input);
}

});
};

function updateCounter(){
Expand All @@ -27,8 +32,14 @@
addInputStyle(isValidLength, $(this));
}

function addCounterElement($input){
var $counterElement = $('<span/>')
function addCounterElement($input) {
var $counterElement = $input.parent().find('span[class="character-counter"]');

if ($counterElement.length) {
return;
}

$counterElement = $('<span/>')
.addClass('character-counter')
.css('float','right')
.css('font-size','12px')
Expand Down

0 comments on commit ef59c12

Please sign in to comment.