'Expanding Text Area throws error on Chrome/Firefox but not Safari

I have a text area that dynamically expands to fit the content inputed. It works correctly on all browsers, as far as I can tell, but on FireFox and Chrome it gives this error in the console:

Uncaught TypeError: Cannot set properties of undefined (setting 'height') at oninput

Here's the code with an example:

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">

I would like this code to run smoothly on all platforms. Additionally I want to make sure I am only targeting textarea and not input, as the error presents if I change a normal input as well.



Solution 1:[1]

You can change the function name with onInput, Or stop event propagation

  function oninput(evt) {
    evt.stopPropagation()
    // ... your code here
  }

The code you wrote above will be converted to below(I guess)


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);
    }
}

Why does the conversion happen? it's one of the quirks of javascript Hoisting

oninput = ... has no scope, in non-strict mode it is scoped to the window, it will be like window.oninput = xxx

Sorry my bad englist

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 1900 TD Lemon