forked from Technigo/js-project-recipe-library
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
201 lines (163 loc) · 6.68 KB
/
Copy pathscript.js
File metadata and controls
201 lines (163 loc) · 6.68 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
const API_KEY = "9db39a66159f43d287c05363e2271c81"
const URL = `https://api.spoonacular.com/recipes/random?number=20&apiKey=${API_KEY}`
const URL2 = `https://api.spoonacular.com/recipes/complexSearch?number=20&sort=random&addRecipeInformation=true&apiKey=${API_KEY}`
// ----------------------------------------------------------
// |||||||||||||||| Show all recipes on page ||||||||||||||||
// ----------------------------------------------------------
const recipeSection = document.querySelector(".recipeSection")
const displayedRecipes = (recipes) => {
recipeSection.innerHTML = ""
if (recipes.length === 0) {
recipeSection.innerHTML = `
<div class="no-matches">
<p>Oops no recipes found...<br> Try something else!</p>
</div>
`
return
}
recipes.forEach(recipe => {
recipeSection.innerHTML += `
<article class="recipe">
<div class="topImageContainer">
<img class="topImage" src="${recipe.image}" alt="photo of food">
<div class="recipeHeadingSection">
<h2 class="recipeHeading">${recipe.title}</h2>
</div>
</div>
<div class="generalInfo">
<ul>
<li class="cuisine"><span>Cuisine:</span> ${recipe.cuisines?.[0] || "No cuisine listed"}</li>
<li class="readyIn"><span>Time:</span> ${recipe.readyInMinutes} min</li>
<li class="readyIn"><span>Health score:</span> ${recipe.healthScore}</li>
</ul>
</div>
<div class="ingredients">
<h3>Ingredients</h3>
<ul>
${recipe.extendedIngredients?.map(ingredient => `<li> ${ingredient.original} </li>`).join("") || "<li>No ingredients available</li>"}
</ul>
</div>
</article>
`
})
}
// --------------------------------------------------------
// |||||||||||||||| Get recipes from API |||||||||||||||||
// --------------------------------------------------------
let recipes = []
const getRecipes = async () => {
try {
const response = await fetch(URL)
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`)
}
const data = await response.json()
recipes = data.recipes
console.log("Recipes fetched from API", data.recipes)
displayedRecipes(recipes)
return true
} catch (error) {
console.error("Failing to fetch API:", error)
return false
}
}
// import backup data from separate file if API limit is reached
import { backupData } from './backupData.js'
const getLocalRecipes = async (backupData) => {
const data = backupData
recipes = data.recipes
console.log("Showing locally stored recipes", data.recipes)
displayedRecipes(recipes)
}
const apiOrLocal = async () => {
const APIWorks = await getRecipes() //Tries to run function getRecipes first (from API)
if (!APIWorks) {
alert("The API credit limit has been reached... But don't worry, showing locally stored recipes instead.")
getLocalRecipes(backupData)
} // if getRecipes function does not work (api has reached a limit), run getLocalRecipes instead.
}
apiOrLocal()
// ----------------------------------------------------------------
// |||||||||||||||| Show filtered recipes on page |||||||||||||||||
// ----------------------------------------------------------------
const dietFilterDropdown = document.getElementById("dietFilterDropdown")
const selectedDiet = () => {
const dietFilter = dietFilterDropdown.value.toLowerCase()
if (dietFilter === "all") {
displayedRecipes(recipes)
} else {
const chosenDiet = recipes.filter(recipe => recipe.diets?.map(diet => diet.toLowerCase()).includes(dietFilter)
)
displayedRecipes(chosenDiet)
}
}
dietFilterDropdown.addEventListener("change", selectedDiet)
const dishFilterDropdown = document.getElementById("dishFilterDropdown")
const selectedDish = () => {
const dishFilter = dishFilterDropdown.value.toLowerCase()
if (dishFilter === "all") {
displayedRecipes(recipes)
} else {
const chosenDish = recipes.filter(recipe => recipe.dishTypes?.map(dish => dish.toLowerCase()).includes(dishFilter))
displayedRecipes(chosenDish)
}
}
dishFilterDropdown.addEventListener("change", selectedDish)
// --------------------------------------------------------
// |||||||||||||||| sort recipes on page ||||||||||||||||||
// --------------------------------------------------------
const sortingButton = document.querySelectorAll(".sortButton")
const fastMeals = document.getElementById("fastMeals")
const popularMeals = document.getElementById("popularMeals")
const cookingTimeDropdown = document.getElementById("cookingTimeDropdown")
const healthScoreDropdown = document.getElementById("healthScoreDropdown")
const cookingTimeSorting = () => {
const chosenCookingTime = cookingTimeDropdown.value
if (chosenCookingTime === "fastMeals") {
displayedRecipes([...recipes].sort((a, b) => a.readyInMinutes - b.readyInMinutes))
} else if (chosenCookingTime === "slowMeals") {
displayedRecipes([...recipes].sort((a, b) => b.readyInMinutes - a.readyInMinutes))
} else {
displayedRecipes(recipes)
}
}
cookingTimeDropdown.addEventListener("change", cookingTimeSorting)
const healthScoreSorting = () => {
const chosenHealthScore = healthScoreDropdown.value
if (chosenHealthScore === "healthyMeals") {
displayedRecipes([...recipes].sort((a, b) => a.healthScore - b.healthScore))
} else if (chosenHealthScore === "unHealthyMeals") {
displayedRecipes([...recipes].sort((a, b) => b.healthScore - a.healthScore))
} else {
displayedRecipes(recipes)
}
}
healthScoreDropdown.addEventListener("change", healthScoreSorting)
// --------------------------------------------------------
// ||||||||||||||||| Get random recipe ||||||||||||||||||||
// --------------------------------------------------------
const randomButton = document.getElementById("randomButton")
const getRandomRecipe = () => {
randomButton.classList.toggle("active")
if (randomButton.classList.contains("active")) {
const randomRecipe = recipes[Math.floor(Math.random() * recipes.length)]
displayedRecipes([randomRecipe])
randomButton.value = "Back to all recipes"
} else {
displayedRecipes(recipes)
randomButton.value = "Random recipe"
}
}
randomButton.addEventListener("click", getRandomRecipe)
// --------------------------------------------------------
// ||||||||||||||||||||| Search bar |||||||||||||||||||||||
// --------------------------------------------------------
const searchInput = document.querySelector("[data-search]")
searchInput.addEventListener("input", e => {
const value = e.target.value.toLowerCase()
const filteredRecipes = recipes.filter(recipe => {
const titleMatch = recipe.title.toLowerCase().includes(value)
return titleMatch
})
displayedRecipes(filteredRecipes)
})