Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 exists in DOM.

In Jquery we can simply do the code below:

$('document').on('click', '.my-button', function () {
    alert("work!!!");
});

But how can I use only Javascript to acheive it? Below is my source code. But after the page loaded, all the new added object doesn't attach a click event.

var Button = document.getElementsByClassName("my-button");
for(i=0;i<Button.length;i++){
    document.getElementsByClassName("my-button")[i].addEventListener("click",function(){
        alert("Work!!!!");
    });
}

Apperciate any suggestion.

like image 890
user3651999 Avatar asked Oct 23 '25 19:10

user3651999


1 Answers

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

<div id="parent">
     <div class="my-button">one</div>
     <div class="my-button">two</div>
     <div class="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

like image 118
Nickydonna Avatar answered Oct 25 '25 08:10

Nickydonna