Search code examples
javascriptfunctioncall

Call a java script function for all targeted elements


I found a javascript function that I want to apply to all targeted elements, in my case all textarea from page but when I am changing the selector from document.getElementById('text'); into document.querySelectorAll('textarea'); or document.getElementsByTagName('textarea') in order to target all elements is not working and I don't understand why, I have tried to put text variable in a for but still not working, if someone can help me a little bit with this dummy issue :|


Solution

  • You were on the right track with a loop, you just didn't go far enough (see comments):

    function init () {
        var list, i, text;
    
        // Get the list
        list = document.getElementsByTagName('textarea');
    
        // Loop through it
        for (i = 0; i < list.length; ++i) {
            // Get this entry
            text = list[i];
    
            // Do things with it
            observe(text, 'change',  resize);
            observe(text, 'cut',     delayedResize);
            observe(text, 'paste',   delayedResize);
            observe(text, 'drop',    delayedResize);
            observe(text, 'keydown', delayedResize);
    
            // Initial `resize` call -- I'm using `.call` in order to
            // set `this` to the element during the call, like an event
            // does
            resize.call(text);
    
            // You'll have to choose *one* of them to focus; I chose the first
            if (i == 0) {
                text.focus();
                text.select();
            }
        }
        function resize () {
            // Note that I'm using `this` here, not `text` or `list`
            // `this` will refer to the element the event is occurring on
            this.style.height = 'auto';
            this.style.height = this.scrollHeight+'px';
        }
    
        // 0-timeout to get the already changed text
        function delayedResize () {
            // Again note the use of `this`, also `.bind`.
            // `Function#bind` creates a function that, when called,
            // calls the original with a specific `this` value
            window.setTimeout(resize.bind(this), 0);
        }
    }