index.js

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.8 kB
7
Indexable
const container = document.querySelector(".container");

function getProduct() {
  fetch("https://dummyjson.com/products")
    .then((response) => response.json())
    .then((response) => {
      const data = response.products;
      data.forEach((item) => {
        createCard(item);
      });
    })
    .catch((error) => console.log(error));
}

function createCard(item) {
  const card = document.createElement("div");
  const card_image = document.createElement("img");
  const card_content = document.createElement("div");
  const card_title = document.createElement("h3");
  const card_price_container = document.createElement("div");
  const card_price = document.createElement("p");
  const card_discount = document.createElement("div");
  const card_rating = document.createElement("div");
  const card_rating_icon = document.createElement("i");
  const card_rating_text = document.createElement("p");

  // Setup element card image
  card_image.src = item.thumbnail;
  card_image.classList.add("card-image");

  // Setup element card content
  card_content.classList.add("card-content");

  // Setup element card title
  card_title.classList.add("card-title");
  card_title.innerHTML = item.title + " - " + item.description;

  // Setup element card price
  card_price_container.classList.add("card-price-container");
  card_price.classList.add("card-price");
  card_price.innerHTML = "$ " + item.price;

  card_discount.classList.add("card-discount");
  card_discount.innerHTML = item.discountPercentage + "%";

  // Setup element card rating
  card_rating.classList.add("card-rating");
  card_rating_icon.classList.add("fa", "fa-star", "card-rating-icon");
  card_rating_text.classList.add("card-rating-text");
  card_rating_text.innerHTML =
    item.rating + " | Tersisa " + item.stock + " pcs";

  // Memasukkan element card image ke dalam element card
  card.appendChild(card_image);

  // Memasukkan element card content ke dalam element card
  card.appendChild(card_content);

  // Memasukkan element card title ke dalam card content
  card_content.appendChild(card_title);

  // Memasukkan element card price container ke dalam card content
  card_content.appendChild(card_price_container);

  // Memasukkan element card price dan card discount ke dalam card price container
  card_price_container.appendChild(card_price);
  card_price_container.appendChild(card_discount);

  // Memasukkan element card rating ke dalam element card content
  card_content.appendChild(card_rating);

  // Memasukkan element card rating icon dan card rating text ke dalam element card rating
  card_rating.appendChild(card_rating_icon);
  card_rating.appendChild(card_rating_text);

  card.classList.add("card");
  container.appendChild(card);

  card.id = item.id;
}

getProduct();