Created
March 11, 2016 21:28
-
-
Save JoeShep/874aaa76d81465a65de6 to your computer and use it in GitHub Desktop.
Attach event listeners via a loop without losing the events
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict" | |
function populatePage (inventory) { | |
// Grab the div we want to apppend the cards to | |
let cards = document.getElementById("inventory-cards"); | |
// Loop over the inventory and populate the page | |
inventory.forEach(function(car, index) { | |
let carCard = buildCard(car, index); | |
let cardDiv = document.createElement("div"); //<---Here's the key to adding the cards with the click event intact | |
cardDiv.innerHTML = (carCard); //Add the created card to the newly created div, instead of directly to the DOM | |
cards.appendChild(cardDiv); // Then add the newly created div to the DOM | |
let card = document.getElementById(`card--${index}`); // Grab the card you just added to the DOM | |
addClickEvent(card); // Attach a click event to it | |
}); | |
// Now that the DOM is loaded, establish all the event listeners needed | |
CarLot.activateEvents(); | |
} | |
function addClickEvent(card) { | |
card.addEventListener("click", function(){ | |
console.log("howdy!"); // Just a test to see if all cards get the click event added | |
}); | |
} | |
function buildCard (car, index) { | |
// Build a string that creates a single card | |
var card = "", | |
card_wrapper = `<section id="card--${index}" class="card-wrapper" style="border: 2px solid ${car.color}">`, | |
card_title = `<h3>${car.year} ${car.make} ${car.model}</h3>`, | |
card_price = `<div class="car-price">$${car.price}</div>`, | |
card_image = `<div class="card-img" style="background-image: url('images/${car.image}')"></div>`, | |
card_sold = car.purchased ? `<span class="card-sold">SOLD!</span>` : "", | |
card_copy = `<p class="card-copy">${car.description}</p>`; | |
// Concatenate our completed card markup | |
card += `${card_wrapper + card_title + card_price + card_image + card_sold + card_copy}</section>`; | |
return card; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment