ogward
ogward

Reputation: 1203

How do I add events to array elements?

My code

var boxes = document.getElementsByClassName("box");
for(var i=0; i<boxes.length;i++)
{
    boxes[i].addEventListener("dblclick", function(e){
        this.classList.add("animateSize");
        this.style.width="2px";
        this.style.height="2px";
        window.setTimeout(2000);
    });
}

Initially I have only one box, then I create more boxes but when I double click any of the newly created boxes nothing happens, only when I double click the initial box the event is triggered.

What am I doing wrong?

PS. When I alert(boxes.length) after I've created, lets say 4 boxes, I get the correct length alerted(5=4 + 1 initial box).

Upvotes: 0

Views: 34

Answers (2)

George
George

Reputation: 36794

Trouble is your code only attaches event handlers for the matches that are currently loaded in the DOM. If this is on DOM load, no 'future' elements will have the event attached.

You could listen for a double click on a static container (I've gone for document) and make a check to see whether the element targeted had the class box. If so, carry out your code:

document.addEventListener("dblclick", function(e){
    if(e.target.classList.contains('box')){
        var box = e.target;
        box.classList.add("animateSize");
        box.style.width="2px";
        box.style.height="2px";
        window.setTimeout(2000);
    }
});

Also known as event delegation.

Note that you'd want to change document for closest static container of your boxes.

There are other ways of course, like attaching your event handlers every time you add your nodes to the DOM.

JSFiddle

Upvotes: 1

Amit Joki
Amit Joki

Reputation: 59292

You need some kind of event delegation. Do this instead.

var parentElem = document.getElementsByClassName("box")[0].parentNode;
parentElem.attachEventHandler("dblclick", function(e) {
    var that = e.target;
    that.classList.add("animateSize");
    that.style.width = "2px";
    // (...) More code
});

Upvotes: 1

Related Questions