Tengo un área de texto que se expande dinámicamente para adaptarse al contenido ingresado. Funciona correctamente en todos los navegadores, por lo que puedo decir, pero en FireFox y Chrome da este error en la consola:
Uncaught TypeError: Cannot set properties of undefined (setting 'height') at oninput
Aquí está el código con un ejemplo:
let ta = document.getElementsByTagName("textarea"); for (let i = 0; i < ta.length; i++) { ta[i].setAttribute("style", "min-height:" + (ta[i].scrollHeight) + "px;overflow-y:hidden;"); ta[i].addEventListener("input", oninput, false); function oninput() { this.style.height = "auto"; let maxheight = 200; if (this.scrollHeight < maxheight){ this.style.height = (this.scrollHeight) + "px"; }else{ this.style.height = maxheight + "px"; } } } <textarea>type here...</textarea> <br><br> <input type="text" placeholder="This should not be affected"> Me gustaría que este código funcione sin problemas en todas las plataformas. Además, quiero asegurarme de que solo estoy apuntando al área de textarea y no a input , ya que el error se presenta si también cambio una entrada normal.
Puede cambiar el nombre de la función con onInput o detener la propagación de eventos
function oninput(evt) { evt.stopPropagation() // ... your code here }El código que escribiste arriba se convertirá a continuación (supongo)
let ta = document.getElementsByTagName("textarea"); for (let i = 0; i < ta.length; i++) { oninput = function() { this.style.height = "auto"; let maxheight = 200; if (this.scrollHeight < maxheight){ this.style.height = (this.scrollHeight) + "px"; }else{ this.style.height = maxheight + "px"; } ta[i].setAttribute("style", "min-height:" + (ta[i].scrollHeight) + "px;overflow-y:hidden;"); ta[i].addEventListener("input", oninput, false); } }¿Por qué ocurre la conversión? Es una de las peculiaridades de javascript Hoisting
oninput = ... no tiene alcance, en modo no estricto está limitado a la ventana, será como window.oninput = xxx
Lo siento mi mal inglés