Converting old JS to event listener

I had an HTML form with a character countdown indicator on a textarea, using old school JavaScript. I have converted this to an event listener but I’m not sure I have done the best job. Can anyone see if I have missed anything? Ta

HTML

<textarea id="message" name="message" placeholder="Your message (up to 500 characters)" required maxlength="500" onkeyup="limitText(this.form.message, this.form.countdown, 500);"></textarea>
<div class="counterBlock">
  <input readonly type="text" name="countdown" value="500" class="counter">
  chars remaining
</div>

Original JS

function limitText(limitField, limitCount, limitNum) {
  if (limitField.value.length > limitNum)
    limitField.value = limitField.value.substring(0, limitNum);
  else
    limitCount.value = limitNum - limitField.value.length;
}

New JS

(function(){
  var limitNum = 500;
  message.onkeyup = function() {
    if ( message.value.length > limitNum )
      message.value = message.value.substring(0, limitNum);
    else
      countdown.value = limitNum - message.value.length;
  }
})();

and of course I have removed the onkeyup from the textarea.

1 Like

Seems you forgot to actually declare and assign message and countdown

var limitNum = 500,
    message = document.getElementById('message'),
    countdown = document.getElementsByClassName('counter')[0];

// ...
1 Like

Thanks @m3g4p0p I thought I was missing something.

1 Like

No you haven’t. All you have done is to pull the event handler out of the HTML and put that in the script without converting it to a listener. To convert it to a listener you’d rewrite it as:

(function(){
  var limitNum = 500,
    message = document.getElementById('message'),
    countdown = document.getElementsByClassName('counter')[0];
  message.addEventListener('keyup', function() {
    if ( message.value.length > limitNum )
      message.value = message.value.substring(0, limitNum);
    else
      countdown.value = limitNum - message.value.length;
  }, false);
})();

Listeners have the advantage over the old style event handlers that your code is still using in that you can attach multiples of the same listener to the same element without the second overwriting the first and you can then remove any of them if required while leaving the others intact.

1 Like

Ah-ha! I see. I think…

Thanks @felgall

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.