Heinlein
Heinlein

Reputation: 35

Attaching single event to multiple elements stored in an array, native JS

Everyone is suggesting some framework, but I'd like to know how it can be done in native JavaScript. I've tried this code and some other things, no effect. Seems that I'm unaware of some basic underlying concept. Any help would be appreciated.

window.onload = function() {
    var trCurrent
    var main = document.getElementById('main');
    var tr = main.getElementsByTagName('tr');
    function hl() {
            trCurrent.setAttribute('class', 'highlight');
    };
    for (var x = 0; x < tr.lenght; x++) { 
        trCurrent = tr[x];
        trCurrent.addEventListener ('mousedown', hl, false);
    }
};

Upvotes: 1

Views: 349

Answers (1)

Rob W
Rob W

Reputation: 349262

  • You have to change trCurrent to this at your function h1, becayse trCurrent points to the last defined TR element (trCurrent = tr[x] for a high x).
  • Use .length instead of .lenght.

Final code:

window.onload = function() {
    var main = document.getElementById('main');
    var tr = main.getElementsByTagName('tr');
    function hl() {
        this.setAttribute('class', 'highlight');
    };
    for (var x = 0; x < tr.length; x++) { 
        tr[x].addEventListener ('mousedown', hl, false);
    }
};

If you want to use an variable which is subject to change during a loop, it's required to wrap the body in an (anonymous) function:

window.onload = function() {
    var main = document.getElementById('main');
    var tr = main.getElementsByTagName('tr');
    for (var x = 0; x < tr.length; x++) {

        (function(trCurrent){ //Anonymous wrapper, first argument: `trCurrent`
            function hl() {
                trCurrent.setAttribute('class', 'highlight');
            };
            trCurrent.addEventListener ('mousedown', hl, false);
        })(tr[x]); //Passing a reference to `tr[x]`
    }
};

Upvotes: 1

Related Questions