As a newcomer to the world of Javascript, I've set myself the challenge of creating an online sales platform. To get started, I'm using the fakestore.com API to populate my site with products. Here's a snippet of my current JavaScript code:
var bestSellers = document.getElementById('mVentes');
var test = document.getElementById('test');
// Making a request to fetch the JSON data of products from fakestore.com
var requestURL = 'https://fakestoreapi.com/products';
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
request.onload = function() {
var superHeroes = request.response;
mSales(superHeroes)
}
// Function to create cards displaying information for the first 3 products
function mSales(prod) {
for (var i = 0; i < 3; i++) {
var card = document.createElement('article');
var image = document.createElement('img');
var title = document.createElement('h3');
var description = document.createElement('p');
var price = document.createElement('h4');
var button = document.createElement('button');
title.textContent = prod[i]['title'];
image.src = prod[i]['image'];
price.textContent = prod[i]['price'] + " €";
button.textContent = "Add to Cart";
// Truncating long descriptions to only display the first 100 characters
var desc = prod[i]['description'];
var text = "";
for(var b = 0; b < 100; b++) {
text = text + desc[b] ;
}
description.textContent = text + "...";
card.appendChild(image);
card.appendChild(title);
card.appendChild(description);
card.appendChild(price);
card.appendChild(button);
bestSellers.appendChild(card);
}
}
...
If someone could help me figure out how to retrieve product information when clicking the "Add to Cart" button, that would be greatly appreciated! PS: Apologies in advance for any awkward translations - French is my primary language! :)