I have created a function in JavaScript which should be run every time the user click a sort option. This has been done using the following code.
function sort() {
let sortByValue = sortBy.value;
let nameAscending = products.sort((a, b) => {
if (a.productName > b.productName) return 1;
if (b.productName > a.productName) return -1;
}); // Sort the product name in ascending order
let nameDescending = products.sort((a, b) => {
if (a.productName > b.productName) return -1;
if (b.productName > a.productName) return 1;
}); // Sort the product name in descending order
if (sortByValue === "name-ascending") {
document.getElementById("products").innerHTML = "";
createCards(products, nameAscending);
}
if (sortByValue === "name-decending") {
document.getElementById("products").innerHTML = "";
createCards(products, nameDescending);
}
let sortBy = document.getElementById("sort-by");
sortBy.onchange = function() {
sort();
}
When I have logged the result of sortByValue to the console, it worked as expected. When I run this function, the div "products" is cleared. However, no new cards are displayed on screen. Why is this?
I have used this function:
function createCards(products) {
for (let i of products) {
//Create Card
let card = document.createElement("div");
//image div
let imgContainer = document.createElement("div");
imgContainer.classList.add("image-container");
//img tag
let image = document.createElement("img");
image.setAttribute("src", i.image);
imgContainer.appendChild(image);
card.appendChild(imgContainer);
document.getElementById("products").appendChild(card);
}
}
By using a debugger, I have found the value of 'sortByValue' is correct on each option click. The program correctly clears the div on any button click. However, the program does not run the createCards function again.