Home > Software design >  Passing an element into a function on load in JavaScript
Passing an element into a function on load in JavaScript

Time:08-07

I would like to add an event listener to a dynamically created object with a class of container. There will be multiple containers on a page and I don’t want to call a function to re add the event listeners to every “container” each time one is created and added to the DOM.

I was hoping for a some way to self reference an element, this way I don’t have to use getElementsByClassName and forEach to add the events, but I can’t get the formatting correct.

I’m hoping for something like:

<div class=“container” onl oad=addEvents(this)>Some Text</div>

Then the JavaScript would be something like

function addEvents(container) {
    container.addEventListener(‘click’, someFunction);
}

Then hopefully, this way it will only add events when new elements are created and loaded in.

CodePudding user response:

You should work with a "delegated" event attachment:

// delegated event attachment:
document.querySelector("body").onclick=ev=>{
  ev.target.tagName=="BUTTON" && document.body.insertAdjacentHTML("beforeEnd",'<div >A new clickable div! <button>another one</button></div>');
  ev.target.classList.contains("container") && console.log("container was clicked!");
}
.container {cursor:pointer}
<div>Something</div>
<div class"abc">else</div>
<div >This one is clickable</div>
<div >This one is not</div>
<div >But this one is clickable again</div>
<div >and so is this</div>
<button>add further clickable containers</button>

This way you define the event attachment on the parental level and every new child element will automatically be clickable - following the selection rules in the actual event handler (note the condition: ev.target.classList.contains("container")!).

  • Related