I create an HTML page using PHP which contains textareas like these:
<div class='table-row'>
<div class='table-cell-left'><!-- ------- instructions -->
<label for='instructions' class='table-label'>short worst-case-scenario instructions.</label>
</div>
<div class='table-cell-right'>
<textarea cols='50' name='instructions' placeholder='short worst-case-scenario instructions.'
maxlength='1000' onkeyup='checkLength(event,1000,"counter"," characters remaining");'
class='timeText'>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</textarea>
</div>
</div>
Not all of them have the "keyup" event, but all input elements share an event which I add at DomReady:
onDOMReady(function(){
addHandlers();
});
function addHandlers(){
var allElements = document.getElementsByTagName("*");
for (i=0; i<allElements.length; i++) {
switch (allElements[i].type && allElements[i].type.toLowerCase()){
case "text":
case "password":
case "email":
break;
case "textarea":
allElements[i].addEventListener("keyup", function(){
checkHeight(allElements[i]);
});
checkHeight(allElements[i]);
break;
}
}
}
function checkHeight(el){
if (el.textLength > 0){
el.style.height = "25px";
el.style.height = (el.scrollHeight)+"px";}
else{
el.rows = 4;
}
}
With this css:
textarea{
display: block;
float: right;
resize: none;
overflow: hidden;
}
all textarea's should be stretched to a minimum of 25px showing all the text in them. If there is no text an empty area of 4 lines is shown.
Now the problem: even though all handlers are correctly added, all textarea heights are correctly set on load, and a change in any textarea activates the checkHeight function, the object type is HTMLLinkElement, instead of HTMLTextAreaElement (which does not have the textLength attribute so the rows are set to 4 but the height is not changed). Also the element type is image/x-icon which makes absolutely no sense to me. Can anyone explain this to me? And maybe suggest a better way?
edit: OK, duplicate is clear, although I never found this in searching. 2 solutions:
for (let i=0; i<allElements.length; i++) { ...
or
case "textarea":
allElements[i].addEventListener("keyup", function(){
checkHeight(this);
});
Thanks!