Calling a jQuery method at declaration time, and then onEvent
- by cesarsalazar
I've been writing JS (mainly jQuery) for quite a few months now, but today I decided to make my first abstraction as a jQuery method. I already have working code but I feel/know that I'm not doing it the right way, so I come here for some enlightenment.
Note: Please do not reply that there's already something out there that does the trick as I already know that. My interest in this matter is rather educational.
What my code is intended to do (and does):
Limit the characters of a textfield and change the color of the counter when the user is approaching the end.
And here's what I have:
$(function(){
  $('#bio textarea').keyup(function(){
    $(this).char_length_validation({
      maxlength: 500,
      warning: 50,
      validationSelector: '#bio .note'
    })
  })
  $('#bio textarea').trigger('keyup');
})
jQuery.fn.char_length_validation = function(opts){
  chars_left = opts.maxlength - this.val().length;
  if(chars_left >= 0){
    $(opts.validationSelector + ' .value').text(chars_left);
    if(chars_left < opts.warning){
      $(opts.validationSelector).addClass('invalid');
    }
    else{
      $(opts.validationSelector).removeClass('invalid');
    }
  }
  else{
    this.value = this.value.substring(0, opts.maxlength);
  }
}
In the HTML:
<div id="bio">
  <textarea>Some text</textarea>
  <p class="note>
    <span class="value">XX</span>
    <span> characters left</span>
  </p>
</div>
Particularly I feel really uncomfortable binding the event each on each keyup instead of binding once and calling a method later.
Also, (and hence the title) I need to call the method initially (when the page renders) and then every time the user inputs a character.
Thanks in advance for your time :)