Mainak Bhattacharjee Mainak Bhattacharjee - 7 months ago 11
Javascript Question

Javascript not working but works fine when put breakpoints and click the file from chrome debugger tools

So i am facing a weird issue. A part of my javascript code which is a function is not working but when i put breakpoints and click the file after going to sources in chrome, the breakpoint starts working and my Javascript function runs perfect.(I can see the output.) Here is my code. Please tell why i am facing this issue?

HTML code.....

<textarea type="text" class="input-content" onchange="count(this)"></textarea>
<p class="character-count"></p>


Javascript

function count(char){
char.onkeyup = function () {
var text_max = 99;
var text_length = this.value.length;
var text_remaining = text_max - text_length;
char.parentNode.getElementsByClassName("character-count")[0].innerHTML = "Character count:" + text_length + "/" + text_max;
}
}

Answer

You are assigning a keyup event handler in an onchange. That will not work since onchange does not trigger until you leave the field. Do it on focus but do not add a new event handler if it already has one.

Note I removed the inline event handler which is not good practice. I loop because I assume you may have more than one field you want to add the counter to.

function count(){
  if (!this.onkeyup) this.onkeyup = function () { 
        var text_max = 99;
        var text_length = this.value.length;
        var text_remaining = text_max - text_length;
        this.parentNode.getElementsByClassName("character-count")[0].innerHTML = "Character count:" + text_length + "/" + text_max;
  }
}
window.onload=function() {
  var msgs = document.querySelectorAll(".input-content");
  for (var i=0;i<msgs.length;i++) {
     msgs[i].onfocus=count;
  }
} 
<div><textarea type="text" class="input-content"></textarea>
<p class="character-count"></p>
</div>

You could do all this onkeyup on its own instead

window.onload=function() {
  var msgs = document.querySelectorAll(".input-content");
  for (var i=0;i<msgs.length;i++) {
     msgs[i].onkeyup=function () { 
        var text_max = 99;
        var text_length = this.value.length;
        var text_remaining = text_max - text_length;
        this.parentNode.getElementsByClassName("character-count")[0].innerHTML = "Character count:" + text_length + "/" + text_max;
    };
  }
} 
<div><textarea type="text" class="input-content"></textarea>
<p class="character-count"></p>
</div>

Comments