Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
1.9 kB
1
Indexable
Never
const catList = catsArray;
const adoptedCats = [];

const shelterSection = document.querySelector('.shelter');
const searchInput = document.querySelector('.searchInput');
const searchButton = document.querySelector('.searchButton');
const sortButton = document.querySelector('.sortButton');

searchButton.addEventListener('click', () => renderAllCats(filterCats(catList)))
sortButton.addEventListener('click', () => renderAllCats(sortCats(catList)))

const filterCats = (cats) => cats.filter(cat => cat.name.toLowerCase().includes(searchInput.value.toLowerCase()));

const sortCats = (cats) => {
    console.log("I am sorting!")
    return cats.sort((a,b) => a.name < b.name ? -1 : 1);
}

const adopt = (cat) => {
    adoptedCats.push(cat);
    console.log("I am adopted!")
    renderAllCats(catList);
}
const renderCat = (cat) => {
    const { name, id, adjective } = cat; // now I can say `name` instead of `cat.name`
    const catCard = document.createElement('section');
    catCard.className = 'card';
    const catName = document.createElement('p');
    catName.innerText = name;
    const catImg = document.createElement('img');
    catImg.src = `img/cat${id}.jpeg`;
    const catDescription = document.createElement('p');

catDescription.innerText = `${name} is ${adjective}`;
    catCard.append(catName, catImg, catDescription);

const catAdopted = document.createElement('p');
    catAdopted.innerText = `${name} was adopted!`;

    const button = document.createElement('button');
    button.innerText = 'Adopt me!';
    button.addEventListener('click', () => adopt(cat));

    const elementToAdd = (adoptedCats.includes(cat)) ? catAdopted : button;
    catCard.append(elementToAdd);
    return catCard;
}

const renderAllCats = (cats) => {
    const elements = cats.map(renderCat);
    shelterSection.replaceChildren(...elements);
}

renderAllCats(catList);