Click here to Skip to main content
15,559,275 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In my code, I have a set of items created in my HTML that when I click on them, new ones come in their place. I am adding these new items dynamically with JavaScript. I have the content stored in an array of objects and and then I am adding a click event to each of the original items. On the click event, it filters through the array to display only certain items. All of the filtered items are added dynamically via innerHTML.

What I would like to do is to be able to click on the dynamically added items to display a whole different set of content. I do realize that because I am using innerHTML I can't use querySelector or getElementById to select a class or id attached to the dynamically added content. The result is null.

After some research, I found that you can bind an event listener or click event to dynamically added content. But I just can't figure out a way do this with the code that I have. Is there a way that I can do this or is there some other way entirely to achieve what I am trying to do?

My code is shown below:
JavaScript
  1  const projectCards = [
  2      {
  3          id: 1,
  4          dataId: "TAFE",
  5          title: "Identity System",
  6          category: "TAFE",
  7          img: "../img/image-plane.jpg",
  8          url: "../pages/graphic_design/tafe/tafe_company_identitySystem.html",
  9      },
 10      {
 11          id: 2,
 12          dataId: "TAFE",
 13          title: "Audition/Show Posters",
 14          category: "TAFE",
 15          img: "../img/image-plane.jpg",
 16          url: "../pages/graphic_design/tafe/tafe_show_posters.html",
 17      },
 18      {
 19          id: 3,
 20          dataId: "TAFE",
 21          title: "Programs",
 22          category: "TAFE",
 23          img: "../img/image-plane.jpg",
 24          url: "../pages/graphic_design/tafe/tafe_show_programs.html",
 25      },
 26      {
 27          id: 4,
 28          dataId: "TAFE",
 29          title: "Tickets",
 30          category: "TAFE",
 31          img: "../img/image-plane.jpg",
 32          url: "../pages/graphic_design/tafe/tafe_show_tickets.html",
 33      },
 34      {
 35          id: 5,
 36          dataId: "TAFE",
 37          title: "Postcards",
 38          category: "TAFE",
 39          img: "../img/image-plane.jpg",
 40          url: "../pages/graphic_design/tafe/tafe_newsletter.html",
 41      },
 42      {
 43          id: 6,
 44          dataId: "TAFE",
 45          title: "Newsletter",
 46          category: "TAFE",
 47          img: "../img/image-plane.jpg",
 48          url: "../pages/graphic_design/tafe/tafe_postcards.html",
 49      },
 50      {
 51          id: 7,
 52          dataId: "CAHQ",
 53          class: "entry-imgText",
 54          title: "Identity System",
 55          category: "CAHQ",
 56          img: "../img/image-currency.jpg",
 57          url: "../pages/graphic_design/cahq/cahq_identity_system.html",
 58      },
 59      {
 60          id: 8,
 61          dataId: "CAHQ",
 62          class: "entry-imgText",
 63          title: "Marketing Materials",
 64          category: "CAHQ",
 65          img: "../img/image-currency.jpg",
 66          url: "../pages/graphic_design/cahq/cahq_identity_system.html",
 67      },
 68      {
 69          id: 9,
 70          dataId: "CAHQ",
 71          class: "entry-imgText",
 72          title: "Website Icons",
 73          category: "CAHQ",
 74          img: "../img/image-currency.jpg",
 75          url: "../pages/graphic_design/cahq/cahq_website_icons.html",
 76      },
 77      {
 78          id: 10,
 79          dataId: "PWC",
 80          class: "entry-imgText",
 81          title: "Identity System",
 82          category: "PWC",
 83          img: "../img/image-restaurant.jpg",
 84          url: "../pages/graphic_design/pilates/pwc_company_identitySystem.html",
 85      },
 86      {
 87          id: 11,
 88          dataId: "PWC",
 89          class: "entry-imgText",
 90          title: "Marketing Materials",
 91          category: "PWC",
 92          img: "../img/image-restaurant.jpg",
 93          url: "../pages/graphic_design/pilates/pwc_marketing_materials.html",
 94      },
 95      {
 96          id: 12,
 97          dataId: "Photo Essays",
 98          class: "entry-imgText",
 99          title: "Columbia-Wrightsville Bridge",
100          category: "Photo Essays",
101          img: "../img/image-restaurant.jpg",
102          url: "../pages/graphic_design/photo_essays/columbia-wrightsville_bridge.html",
103      },
104      {
105          id: 13,
106          dataId: "Photo Essays",
107          class: "entry-imgText",
108          title: "Shift Focus",
109          category: "Photo Essays",
110          img: "../img/image-currency.jpg",
111          url: "../pages/graphic_design/photo_essays/shift_focus.html",
112      },
113      {
114          id: 14,
115          dataId: "Photo Essays",
116          class: "entry-imgText",
117          title: "A Commuter's View",
118          category: "Photo Essays",
119          img: "../img/image-plane.jpg",
120          url: "../pages/graphic_design/photo_essays/a_commuters_view.html",
121      }
122  ];
123  
124  let projects = [
125      {
126          id: 1,
127          dataId: "TAFE",
128          title: "Identity System",
129          description: 'Lorem, ipsum dolor sit amet consectetur adipisicing elit. Nulla tenetur ab odio. Rerum cumque distinctio eveniet illum ea omnis non iure repudiandae labore quas aut optio aliquam dolorem, delectus doloribus!',
130          date: '2016 - present',
131          client: 'TAFE (Theater Arts For Everyone)',
132          role: 'Graphic Designer',
133          projectType: 'Layout (color + graphics)',
134          programClass1: 'ai',
135          programClass2: 'id',
136          program1: 'Ai', 
137          program2: 'Id', 
138          category: "1",
139          img: "../img/image-plane.jpg",
140      },
141      {
142          id: 2,
143          dataId: "2",
144          title: "Identity System",
145          description: 'Lorem, ipsum dolor sit amet consectetur adipisicing elit. Nulla tenetur ab odio. Rerum cumque distinctio eveniet illum ea omnis non iure repudiandae labore quas aut optio aliquam dolorem, delectus doloribus!',
146          date: '2016 - present',
147          client: 'TAFE (Theater Arts For Everyone)',
148          role: 'Graphic Designer',
149          projectType: 'Layout (color + graphics)',
150          programClass1: 'ai',
151          programClass2: 'id',
152          program1: 'Ai', 
153          program2: 'Id', 
154          category: "2",
155          img: "../img/image-currency.jpg",
156      },
157  
158      {
159          id: 2,
160          dataId: "2",
161          title: "Identity System",
162          description: 'Lorem, ipsum dolor sit amet consectetur adipisicing elit. Nulla tenetur ab odio. Rerum cumque distinctio eveniet illum ea omnis non iure repudiandae labore quas aut optio aliquam dolorem, delectus doloribus!',
163          date: '2016 - present',
164          client: 'TAFE (Theater Arts For Everyone)',
165          role: 'Graphic Designer',
166          projectType: 'Layout (color + graphics)',
167          programClass1: 'ai',
168          programClass2: 'id',
169          program1: 'Ai', 
170          program2: 'Id', 
171          category: "2",
172          img: "../img/image-restaurant.jpg",
173      },
174      
175  ];
176  
177  const portfolioHeadingContainer = document.getElementById('portfolio__headingContainer');
178  const portfolioContentContainer = document.getElementById('portfolio_content_container');
179  
180  const buttonContainer = document.querySelector('button-container');
181  const filterProjects = document.querySelectorAll('.filter-projects');
182  const projectsBtn = document.querySelectorAll('.projects-btn');
183  const portfolioGrid = document.querySelector('.portfolio__grid');
184  const portfolioContent = document.querySelector('.portfolio__content'); 
185  
186  // filter project items
187  filterProjects.forEach(function(btn) {
188      btn.addEventListener('click', function(e) {
189          const category = e.currentTarget.dataset.id;
190          const projectCategory = projectCards.filter(function(projectItem) {
191              if(projectItem.category === category) {
192                  return projectItem;
193              }
194          });
195          if(category === "all") {
196              displayProjectItems(projectCards);
197          } 
198          else {
199              displayProjectItems(projectCategory);
200          }
201  
202      });
203  
204  });
205  
206  
207  // active
208  projectsBtn.forEach(button => {
209      button.addEventListener('click', function(){
210          projectsBtn.forEach(btn => btn.classList.remove('active'));
211          this.classList.add('active');
212      });
213  });
214  
215  function displayProjectItems(projectItems) {
216      let displayProjectItem = projectItems.map(function(item) {
217          return `
218              
219              
220                  ${item.title}
221               
222          `;
223  
224      });
225  
226      let displayTitle = projectItems.map(function(titleItem) {
227          return `${titleItem.category}`;
228      });
229  
230  
231      displayProjectItem = displayProjectItem.join("");
232      portfolioGrid.innerHTML = displayProjectItem;
233  
234      displayTitle = displayTitle.join("");
235      portfolioHeadingContainer.innerHTML = displayTitle;
236  }
HTML
  1  <div id="portfolio_content_container">
  2      <div class="portfolio__grid">
  3  
  4           <!------------ Item 1 ------------>
  5          <a href="#" class="portfolio__item filter-projects" data-id="TAFE">
  6              <img class="portfolio__image" src="../img/image-confetti.jpg" alt="TAFE logo" />
  7              <div class="portfolio__clientName">
  8                  <h3 class="portfolio__clientName-text">TAFE (Theatre Arts For Everyone)</h3>
  9              </div> <!-- end portfolio__clientName -->
 10          </a>
 11  
 12          <!------------ Item 2 ------------>
 13          <a href="#" class="portfolio__item filter-projects" data-id="CAHQ">
 14              <img class="portfolio__image" src="../img/image-confetti.jpg" alt="CAHQ Brochure" />
 15              <div class="portfolio__clientName">
 16                  <h3 class="portfolio__clientName-text">College Admissions HQ</h3>
 17              </div> <!-- end portfolio__clientName -->
 18          </a>
 19  
 20          <!------------ Item 3 ------------>
 21          <a href="#" class="portfolio__item filter-projects" data-id="PWC">
 22              <img class="portfolio__image" src="../img/image-confetti.jpg" alt="pilates wellness center logo" />
 23              <div class="portfolio__clientName">
 24                  <h3 class="portfolio__clientName-text">Pilates Wellness Center of York</h3>
 25              </div> <!-- end portfolio__clientName -->
 26          </a>
 27  
 28          <!------------ Item 4 ------------>
 29          <a href="../pages/graphic_design/jane_daisy_general/jane_daisy_general.html" class="portfolio__item filter-projects" data-id=JDG">
 30              <img class="portfolio__image" src="../img/image-confetti.jpg" alt="jane dasie general logo" />
 31              <div class="portfolio__clientName">
 32                  <h3 class="portfolio__clientName-text">Jane Daisy General</h3>
 33              </div> <!-- end portfolio__clientName -->
 34          </a>
 35  
 36          <!------------ Item 5 ------------>
 37          <a href="../pages/graphic_design/secondEncounter/secondEncounter.html" class="portfolio__item filter-projects" data-id="secondEncounter">
 38              <img class="portfolio__image" src="../img/image-confetti.jpg" alt="secondEncounter logo" />
 39              <div class="portfolio__clientName">
 40                  <h3 class="portfolio__clientName-text">secondEncounter</h3>
 41              </div> <!-- end portfolio__clientName -->
 42          </a>
 43  
 44          <!------------ Item 6 ------------>
 45          <a href="#" class="portfolio__item filter-projects" data-id="DB">
 46              <img class="portfolio__image" src="../img/image-confetti.jpg" alt="Dobbs & Bishop" />
 47              <div class="portfolio__clientName">
 48                  <h3 class="portfolio__clientName-text">Dobbs & Bishop Fine Cheese</h3>
 49              </div> <!-- end portfolio__clientName -->
 50          </a>
 51  
 52          <!------------ Item 7 ------------>
 53          <a href="../pages/graphic_design/yorkfest/yorkfest.html" class="portfolio__item filter-projects" data-id="Yorkfest">
 54              <img class="portfolio__image" src="../img/image-confetti.jpg" alt="Yorkfest Logo" />
 55              <div class="portfolio__clientName">
 56                  <h3 class="portfolio__clientName-text">Yorkfest</h3>
 57              </div> <!-- end portfolio__clientName -->
 58          </a>
 59  
 60          <!------------ Item 8 ------------>
 61          <a href="../pages/graphic_design/lish/lish.html" class="portfolio__item filter-projects" data-id="Lish"> 
 62              <img class="portfolio__image" src="../img/image-confetti.jpg" alt="Lish Logo" />
 63              <div class="portfolio__clientName">
 64                  <h3 class="portfolio__clientName-text">Lish</h3>
 65              </div> <!-- end portfolio__clientName -->
 66          </a>
 67  
 68          <!------------ Item 9 ------------>
 69          <a href="#" class="portfolio__item filter-projects" data-id="Photo Essays">
 70              <img class="portfolio__image" src="../img/image-confetti.jpg" alt="Columbia-Wrightsville Bridge Book Cover" />
 71              <div class="portfolio__clientName">
 72                  <h3 class="portfolio__clientName-text">Photo Essays</h3>
 73              </div> <!-- end portfolio__clientName -->
 74          </a>
 75  
 76      </div> <!-- end portfolio__grid--> 
 77      <div class="button-container-bottom">
 78          <a class="filter-projects active" type="button" data-id="graphicDesign">Graphic Desing</a>
 79          <a class="filter-projects" type="button" data-id="webDesign">Web Design</a>
 80      </div>  
 81  </div> <!-- end portfolio_content_container -->


What I have tried:

I have tried binding a click event in so many different ways. I just can't figure out how to get it to work with my code.
Posted
Updated 7-Jun-21 23:05pm
v2

1 solution

You can't retrieve an element from the document until it has been added. You'll need to use delegated events instead:
Event delegation[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900