Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"liveServer.settings.port": 5501
}
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
# js-project-recipe-library

netlify link: https://carolinas-recipe-library.netlify.app/
Binary file added img/French-toast.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added img/beef-stew.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added img/lentil-soup.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added img/pasta-pesto.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
105 changes: 105 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta
name="viewport"
content="width=device-width, initial-scale=1.0"
>
<link
rel="stylesheet"
href="style.css"
>
<title>Carolinas recipe library</title>
</head>

<body>
<h1>Recipe library</h1>
<!-- filters -->
<div class="filter-row">
<div class="meal-filter-container">
<h2>Meals</h2>
<div class="meal-buttons-container">
<button
class="meal-btn"
id="btnAll"
>All</button>
<button
class="meal-btn"
id="btnBreakfast"
>Breakfast</button>
<button
class="meal-btn"
id="btnLunch"
>Lunch</button>
<button
class="meal-btn"
id="btnFika"
>Fika</button>
<button
class="meal-btn"
id="btnDinner"
>Dinner</button>
Comment on lines +24 to +43

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I understand why the buttons are broken over multiple lines, but since there’s no nested content or long attributes, it might be cleaner to keep each on a single line for readability.

Like

Button text instead :D

</div>
<!-- sorting -->
</div>
<div class="sorting-time-container">
<h2>Cooking time</h2>
<div class="time-buttons-container">
<button
class="time-btn"
id="btnAscending"
>Ascending</button>
<button
class="time-btn"
id="btnDescending"
>Descending</button>
</div>
</div>
<!-- random recipe filter -->
<div class="random-recipe-container">
<h2>Random recipe</h2>
<button
class="random-btn"
id="btnRandom"
>Suprise!</button>
</div>
<!-- search bar -->
<div class="search-feature-container">
<h2>Search for recipes:</h2>
<div class="search-bar-container">
<input
class="search-bar"
id="searchBar"
type="search"
placeholder="Search..."
>
<button
class="search-button"
id="searchBtn"
>🔎</button>
</div>
</div>
</div>
<!-- loading message -->
<div
class="loading"
id="loading"
>
<p>Loading recipes... 🍳</p>
</div>
<!-- recipe cards -->
<div
class="recipe-card-container"
id="recipeContainer"
></div>
<!-- no results text -->
<div
class="no-results-container"
id="noResultsContainer"
></div>
<script src="script.js"></script>
</body>

</html>
215 changes: 215 additions & 0 deletions script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
// ====== DOM SELECTORS ======
const btnAll = document.getElementById("btnAll")
const btnBreakfast = document.getElementById("btnBreakfast")
const btnLunch = document.getElementById("btnLunch")
const btnFika = document.getElementById("btnFika")
const btnDinner = document.getElementById("btnDinner")
const btnAscending = document.getElementById("btnAscending")
const btnDescending = document.getElementById("btnDescending")
const mealBtns = document.querySelectorAll(".meal-btn")
const timeBtns = document.querySelectorAll(".time-btn")
const randomBtn = document.getElementById("btnRandom")
const recipeContainer = document.getElementById("recipeContainer")
const noResultsContainer = document.getElementById("noResultsContainer")
const loading = document.getElementById("loading")
const searchInput = document.getElementById("searchBar")
const searchBtn = document.getElementById("searchBtn")
Comment on lines +2 to +16

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clean structure to find the DOM selectors!


// ====== API SETTINGS ======
const URL = `https://api.spoonacular.com/recipes/random?number=15&apiKey=4d3e2b2a43464de48c4a0aac3abf2c52`

// ====== GLOBAL STATE ======
let recipeInfo = []
let activeFilters = {
mealType: "All",
sortOrder: null
}

// ====== DISPLAY FUNCTIONS ======
const showRecipes = (recipesToShow) => {
recipeContainer.innerHTML = ``

recipesToShow.forEach(recipe => {
recipeContainer.innerHTML += `
<div class="recipe-card">
<img src="${recipe.image}" alt="${recipe.title}">
<h3>${recipe.title}</h3>
<hr>

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure I would do an


here — it introduces an extra DOM element and forces a visual line even if future designs might not include one. Since the goal is just a horizontal divider, it might be more flexible and semantic to use a CSS border or pseudo-element instead. That way, you can easily adjust or remove the line in future design updates without changing the HTML structure.

<h4>
<span class="label">Meal:</span>
<span class="value">${recipe.dishTypes?.join(", ") || "N/A"}</span><br>
<span class="mealLabel">Cooking time:</span>
<span class="value">${recipe.readyInMinutes} min</span>
</h4>
<hr>
<h4>Ingredients</h4>
<p>${recipe.extendedIngredients
? recipe.extendedIngredients.map(ing => `${ing.name}`).join("<br>")
: "No ingredients listed"
}</p>
</div>`
})
}

// ====== FILTERING & SORTING ======
const filterAndSorting = () => {
let filtered = [...recipeInfo]

// Filter by meal type
if (activeFilters.mealType && activeFilters.mealType !== "All") {
filtered = filtered.filter(recipe => recipe.dishTypes?.includes(activeFilters.mealType))

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

}

// Sort by time (ascending or descending)
if (activeFilters.sortOrder === "asc") {
filtered.sort((a, b) => a.readyInMinutes - b.readyInMinutes)
} else if (activeFilters.sortOrder === "desc") {
filtered.sort((a, b) => b.readyInMinutes - a.readyInMinutes)
}

// Display filtered results or show a message if none found
if (filtered.length > 0) {
noResultsContainer.innerHTML = ``
showRecipes(filtered)
} else {
recipeContainer.innerHTML = ``
noResultsContainer.innerHTML = `
<div class="no-results-container">
<h3>No recipes found for "${activeFilters.mealType}"</h3>
<p>Try another filter</p>
</div>`
Comment on lines +76 to +80

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good UX

}
}

// ====== SEARCH ======
const searchRecipes = () => {
const query = searchInput.value.trim().toLowerCase()
if (!query) {
filterAndSorting()
return
}

let filtered = [...recipeInfo]

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⭐ using spread operator!


if (activeFilters.mealType && activeFilters.mealType !== "All") {
filtered = filtered.filter(recipe =>
recipe.dishTypes?.includes(activeFilters.mealType)
)
}

filtered = filtered.filter(recipe => {
const titleMatch = recipe.title.toLowerCase().includes(query)
const ingredientsMatch = recipe.extendedIngredients?.some(ing =>
ing.name.toLowerCase().includes(query)
)
return titleMatch || ingredientsMatch
})

if (filtered.length > 0) {
noResultsContainer.innerHTML = ``
showRecipes(filtered)
} else {
recipeContainer.innerHTML = ``
noResultsContainer.innerHTML = `
<div class="no-results-container">
<h3>No recipes found matching "${query}"</h3>
<p>Try another search term or combination of filters.</p>
</div>`
}
}

// ====== RANDOM RECIPE FEATURE ======
const getRandomRecipe = () => {
const randomIndex = Math.floor(Math.random() * recipeInfo.length)
const randomRecipe = recipeInfo[randomIndex]
showRecipes([randomRecipe])
}

// ====== DATA FETCHING (with caching + error handling) ======
const fetchData = async (URL) => {
loading.style.display = "block"
recipeContainer.innerHTML = ``
noResultsContainer.innerHTML = ``

try {
const cachedData = localStorage.getItem("cachedRecipes")
const cacheTime = localStorage.getItem("cacheTime")

const now = Date.now()
const sixHours = 6 * 60 * 60 * 1000 // cache duration

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice with setting a duration for cache

Comment on lines +129 to +139

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.


// Use cache if still valid
if (cachedData && cacheTime && now - cacheTime < sixHours) {
recipeInfo = JSON.parse(cachedData)
loading.style.display = "none"

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

like the way you're handling the loading state

filterAndSorting()
} else {
// Otherwise, fetch new data
const response = await fetch(URL)

// Handle API quota errors
if (!response.ok) {
if (response.status === 402 || response.status === 429) {
loading.style.display = "none"
recipeContainer.innerHTML = ``
noResultsContainer.innerHTML = `
<div class="no-results-container">
<h3>Daily API quota reached</h3>
<p>Spoonacular limits the number of requests per day.
Please try again later or use cached results if available.</p>
</div>`
return
} else {
throw new Error(`HTTP error ${response ? response.status : "unknown"}`)
}
}

const data = await response.json()
recipeInfo = data.recipes

// Save to cache
localStorage.setItem("cachedRecipes", JSON.stringify(recipeInfo))
localStorage.setItem("cacheTime", Date.now())

loading.style.display = "none"
filterAndSorting()
}
} catch (err) {
loading.style.display = "none"
noResultsContainer.innerHTML = `
<div class="no-results-container">
<h3>Something went wrong</h3>
<p>${err.message || "Unable to load recipes right now. Please try again later."}</p>
</div>`
}
}

// ====== EVENT LISTENERS ======
btnAll.addEventListener("click", () => { activeFilters.mealType = "All"; filterAndSorting() })
btnBreakfast.addEventListener("click", () => { activeFilters.mealType = "breakfast"; filterAndSorting() })
btnLunch.addEventListener("click", () => { activeFilters.mealType = "lunch"; filterAndSorting() })
btnFika.addEventListener("click", () => { activeFilters.mealType = "fika"; filterAndSorting() })
btnDinner.addEventListener("click", () => { activeFilters.mealType = "dinner"; filterAndSorting() })
btnAscending.addEventListener("click", () => { activeFilters.sortOrder = "asc"; filterAndSorting() })
btnDescending.addEventListener("click", () => { activeFilters.sortOrder = "desc"; filterAndSorting() })
randomBtn.addEventListener("click", getRandomRecipe)
searchBtn.addEventListener("click", searchRecipes)
searchInput.addEventListener("keypress", (e) => { if (e.key === "Enter") searchRecipes() })
Comment on lines +188 to +197

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good grouping of event listeners 👍 — one thought is that as this logic scales, it could be more maintainable to encapsulate these within a component or a setup function related to the feature (e.g. initMealFilters() or similar). That way, each feature owns its own event bindings.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adding on to the comment here.
If you want to refactor this could be an option:

Create a helper function that updates the activeFilters object with the given properties, then run the filterAndSorting function

const applyFilters = updates => {
  Object.assign(activeFilters, updates)
  filterAndSorting()
}

You can create something called a Map that pairs each button element with its meal type (read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)

const mealButtons = new Map([
  [btnAll, 'All'],
  [btnBreakfast, 'breakfast'],
  [btnLunch, 'lunch'],
  [btnFika, 'fika'],
  [btnDinner, 'dinner']
])

Then loop through the Map
for each [button, mealType] pair, add a click listener
when clicked, it updates activeFilters.mealType and calls filterAndSorting()

mealButtons.forEach((mealType, btn) => {
  btn.addEventListener('click', () => applyFilters({ mealType }))
})

Have a read thru if you want to, for future reference.


// ====== INITIAL FETCH ======
fetchData(URL)

// ====== BUTTON STATE TOGGLE ======
mealBtns.forEach(clickedButton => {
clickedButton.addEventListener("click", () => {
mealBtns.forEach(currentButton => currentButton.classList.remove("active"))
clickedButton.classList.add("active")
})
})

timeBtns.forEach(clickedButton => {
clickedButton.addEventListener("click", () => {
timeBtns.forEach(currentButton => currentButton.classList.remove("active"))
clickedButton.classList.add("active")
})
})
Loading