Skip to content Skip to sidebar Skip to footer

Addeventlistener To Not Exists Object With Only Javascript

I search for the whole stackoverflow but I didn't get any good result against this issues.Correct me if i'm wrong. I want to addEventListener to object that exists or haven't exist

Solution 1:

jQuery does not add the event listener to each div, it attaches it to the parent.

What you can do is attach the event to the parent, and in the event handler, see it the target is one of the buttons, then run your function

HTML

<divid="parent"><divclass="my-button">one</div><divclass="my-button">two</div><divclass="my-button">three</div></div>

JS

document.getElementById("parent").addEventListener("click", function(event) {
     if ( event.target.className === 'my-button') {
          //Do your magic
     }
});

This way, every button you add will run your function. I don't know if the event target has the className attribute, but I suppose is rather simple to get the element based on the event.target object. Remember that older IE won't have the addEventListener function. Check here EventTarget.addEventListener - Web API Interfaces | MDN

Solution 2:

Well, first off you don't need the second document.getElementsByClssName, secondly IE has a special function.

var buttons = document.getElementsByClassName("my-button");
for(i=0;i<buttons.length;i++){


    // For modern browsersif( buttons[i].addEventListener ) {
        buttons[i].addEventListener("click",function(){
            alert("Work!!!!");
        }, false );
    }

    // For outdated IEelseif( buttons[i].attachEvent ) {
        buttons[i].attachEvent("onclick",function(){
            alert("Work!!!!");
        });
    }
}

EDIT:

You could also use buttons array as something you create on the fly, ie :

var button1 = document.createElement( 'button' );
var button2 = document.createElement( 'button' );
var buttons = [ button1, button2 ]

// Rest of code above

Post a Comment for "Addeventlistener To Not Exists Object With Only Javascript"