0

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.

  • Did you debug and see if it goes into an if? console.log(), break points, and debugger are your friend. – epascarello Mar 06 '23 at 20:30
  • You're declaring `sortBy` variable twice. According to this [answer](https://stackoverflow.com/questions/68355442/javascript-let-double-declaration) Chrome console.log allows multiple let declarations, but this should be an issue when running function. Change `let sortBy` to just `sortBy` at the end if you need to change the value. – Key Mar 06 '23 at 20:59

0 Answers0