Javascript only listens for events at the last node specified

So, I am working on a simple gui. The problem is that ONLY the last one is textareaaffected by the script. All previous ones do not react at all. (check screenshot)

document.addEventListener("DOMContentLoaded", function (){

// Interactive textareas
var txta = document.getElementsByTagName('textarea');
for (var i = 0; i < txta.length; i++){
    var earse = txta[i].value;
    console.log(earse); // debugging
    txta[i].addEventListener('focus', function(e){
        if (e.target.value === earse) {
            e.target.value = "";
            e.target.addEventListener('blur', function(e){
                if (e.target.value === "") {
                    e.target.value = earse;
                }
            }, false);
        }
    }, false);
    console.log(txta[i]); // debugging
};

}, false);

Screenshot ( http://i.imgur.com/HTsMypB.jpg ):screenshot

Html is just a few simple ones textareawith the value specified in html.

0
source share
1 answer

Closing the internal function:

document.addEventListener("DOMContentLoaded", function (){

// Interactive textareas
var txta = document.getElementsByTagName('textarea');
for (var i = 0; i < txta.length; i++){
    var earse = txta[i].value;
    console.log(earse); // debugging
    (function(earse){
            txta[i].addEventListener('focus', function(e){
                    if (e.target.value === earse) {
                            e.target.value = "";
                            e.target.addEventListener('blur', function(e){
                                    if (e.target.value === "") {
                                            e.target.value = earse;
                                    }
                            }, false);
                    }
            }, false);
        })(earse);
    console.log(txta[i]); // debugging
};

}, false);

http://jsfiddle.net/WjV8n/

For comments: you need a closed vibrating bruise inside the loop. Because every step you change this variable.

+1
source

Source: https://habr.com/ru/post/1536107/


All Articles