Skip to content

Instantly share code, notes, and snippets.

@SandyWyper
Last active April 18, 2019 10:02
Show Gist options
  • Save SandyWyper/ad3fa12ac18a3c5dacdd199fb90f4514 to your computer and use it in GitHub Desktop.
Save SandyWyper/ad3fa12ac18a3c5dacdd199fb90f4514 to your computer and use it in GitHub Desktop.
Event Delegation of dynamically added content.
function insertContent(results) {
let content = document.getElementById('inserted-content');
results.forEach(function(res) {
content.innerHTML += `
<div class="total-insert">
<div class="header-content">
<h1>This is the title</h1>
<div class="more-info"> //perhaps append data-thing-id="${res.id}"
<h3>More</h3>
<h3>Info</h3>
</div>
</div>
<div class="hidden-content"> //perhaps tag on the id to this class too
<p>some more info about a thing</p>
</div>
</div>
`;
}
document.addEventListener('click', dealWithClick);
function dealWithClick(event) {
if(!event.target.matches('.more-info')) return;
event.preventDefault();
// take the id from the div that was clicked -
// get the specific "hidden-content-area" and toggle a "hide" class
// or target.hidden or something.
}

Event Delegation

Here's the problem..

  • Content is created with a forEach loop over an array of JSON results from an API
  • Want content to appear as headings, and when user clicks on "more-info" that section is revealed.
    • each repetition of the content may need a unique id so that the apropriate section can be revealed.

When using 'event.target' the click sometimes registers on the text inside the div and not on the whole section. If I add a specific listener then the click will bubble up to the parent and trigger the listener, but I can not create the listeners on the fly when adding the content as it seems to overide each listener with the next. So only the last one created is active once the content has finished loading.

I bet this is a really common thing to deal with but cant find a good answer. Help!!

<div id="inserted-content">
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment