-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
63 lines (52 loc) · 2.25 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
const template = document.querySelector("#pet-card-template")
const wrapper = document.createDocumentFragment()
const start = async () => {
const weatherPromise = await fetch("https://api.weather.gov/gridpoints/MFL/110,50/forecast")
const weatherData = await weatherPromise.json()
const temp = weatherData.properties.periods[0].temperature
const temperature = document.querySelector("#temperature-output")
temperature.textContent = temp
}
start()
const petsArea = async () => {
const petsDataPromise = await fetch("https://animated-dodol-efe41f.netlify.app/.netlify/functions/pets")
const petsData = await petsDataPromise.json()
petsData.forEach(pet => {
const clone = template.content.cloneNode(true)
clone.querySelector(".pet-card").dataset.species = pet.species
clone.querySelector("h3").textContent = pet.name
clone.querySelector(".pet-description").textContent = pet.description
clone.querySelector(".pet-age").textContent = createAgeText(pet.birthYear)
if (!pet.photo) pet.photo = "images/fallback.jpg"
clone.querySelector(".pet-card-photo img").src = pet.photo
clone.querySelector(".pet-card-photo img").alt = `A ${pet.species} named ${pet.name}`
wrapper.appendChild(clone)
})
document.querySelector(".list-of-pets").appendChild(wrapper)
}
petsArea()
const createAgeText = birthYear => {
const age = new Date().getFullYear() - birthYear
const ageText = age == 0 ? "Less than a year old" : age == 1 ? "1 year old" : `${age} years old`
return ageText
}
// pet filter button code
const allButtons = document.querySelectorAll('.pet-filter button')
allButtons.forEach(el => {
el.addEventListener("click", handleButtonClick)
})
function handleButtonClick (e) {
// remove active class from any and all buttons
allButtons.forEach(el => el.classList.remove('active'))
// add active class to the button that got clicked
e.target.classList.add("active")
// actually filter the pets down below
const currentFilter = e.target.dataset.filter
document.querySelectorAll(".pet-card").forEach(el => {
if (currentFilter == el.dataset.species || currentFilter == "all") {
el.style.display = "grid"
} else {
el.style.display = "none"
}
})
}