Creating a Recipe Book App Using HTML, CSS, and JavaScript

Faraz

By Faraz -

Integrate Food & Recipe API into your culinary project. A step-by-step guide to creating an interactive recipe book app using HTML, CSS, and JavaScript.


Creating a Recipe Book App Using HTML, CSS, and JavaScript.jpg

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Preview
  6. Conclusion

Cooking and coding, two seemingly distinct domains, can intertwine to create something truly captivating. In this comprehensive guide, we're about to embark on a journey where gastronomy meets technology. Together, we'll delve into the art of designing and developing a digital recipe book using HTML, CSS, and JavaScript, spiced up with the integration of a Food & Recipe API.

Have you ever wished to share your culinary expertise, your secret family recipes, or your innovative kitchen experiments with the world? Or perhaps you're a coding enthusiast looking to apply your skills to a deliciously creative project? Look no further – this tutorial is your gateway to crafting an interactive platform where recipes are more than just instructions; they're experiences waiting to be savored.

In the digital age, everything has gone online, recipes included. Think about it – no more flipping through worn-out cookbooks or deciphering handwritten recipe cards. Imagine a user-friendly digital recipe book that not only presents recipes with mouthwatering images but also allows for interactivity. That's exactly what we'll be building together.

As you follow along, you'll learn the essential steps to create this captivating fusion of culinary delight and technological innovation. From setting up your project structure and creating visually appealing recipe cards to implementing interactive elements with JavaScript, you'll be in full control. 

In the coming sections, we'll break down each step into digestible portions (pun intended). By the end, you'll not only have a functional digital recipe book but also a deeper understanding of how HTML, CSS, and JavaScript come together to craft engaging user experiences. Plus, with the integration of a Food & Recipe API, your recipe book will always be brimming with fresh ideas to tantalize taste buds.

Whether you're an aspiring chef, a coding aficionado, or simply someone who loves exploring new horizons, this tutorial is designed for you. So, grab your apron and dust off your coding skills – it's time to create a recipe book that's as delightful to browse as it is to cook from. Let's dive into the world where culinary arts and coding prowess collide, creating a symphony of flavors and functions.

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our recipe book.

After creating the files just paste the following codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.

Let me break it down step by step:

1. <!DOCTYPE html>: This declaration defines the document type and version of HTML being used. In this case, it's HTML5.

2. <html lang="en">: This tag indicates the beginning of the HTML document and specifies the language of the content, which is English in this case.

3. <head>: The head section of the document contains metadata about the webpage, like character encoding, title, stylesheets, and other resources. It doesn't display directly on the webpage.

  • <meta charset="UTF-8" />: This sets the character encoding of the document to UTF-8, which supports a wide range of characters and symbols from different languages.
  • <meta http-equiv="X-UA-Compatible" content="IE=edge" />: This meta tag tells Internet Explorer to use the latest rendering engine available.
  • <meta name="viewport" content="width=device-width, initial-scale=1.0" />: This meta tag ensures that the webpage is properly scaled and displayed on various devices, adapting to different screen sizes.
  • <title>Recipe Book App</title>: This sets the title of the webpage, which is typically displayed in the browser's title bar or tab.
  • <link rel="stylesheet" href="styles.css" />: This links an external stylesheet named "styles.css" to the HTML document. Stylesheets are used to define the visual appearance of the webpage.

4. <body>: The body section contains the visible content of the webpage.

  • <header>: This defines a header section for the page.
  • <h1>Recipe Book App</h1>: This is a level 1 heading, indicating the main title of the webpage. It reads "Recipe Book App".
  • <div class="container">: A <div> element with the class "container". It's often used to group and style content within a specific section.
  • <ul id="recipe-list" class="recipe-list">: This is an unordered list (a bulleted list) with the ID "recipe-list" and the class "recipe-list". It will be used to display a list of recipes.
  • </ul>: Closes the unordered list.

5. <script src="script.js"></script>: This includes an external JavaScript file named "script.js" which is used to add interactivity and dynamic behavior to the webpage.

This is the basic structure of our recipe book using HTML, and now we can move on to styling it using CSS.

Step 2 (CSS Code):

Once the basic HTML structure of the recipe book is in place, the next step is to add styling to the recipe book using CSS.

Next, we will create our CSS file. In this file, we will use some basic CSS rules to create our recipe book.

Here's a breakdown of what each part of the code does:

1. Styling the Body:

  • The body element is targeted to set some basic styles for the entire webpage.
  • margin: 0; padding: 0; removes any default margin and padding from the body, effectively creating a clean starting point.
  • font-family: Arial, sans-serif; sets the font family for the entire page to Arial or any sans-serif font if Arial is not available.

2. Styling the Header:

  • The header element is targeted to style the webpage's header section.
  • background: #0c2461; sets the background color to a dark blue shade.
  • color: #fff; sets the text color to white.
  • padding: 20px; adds 20 pixels of padding around the header.
  • text-align: center; centers the text within the header.

3. Styling Headings (h1):

  • h1 elements are targeted to style main headings.
  • margin: 0; removes any margin around the heading.
  • font-size: 36px; sets the font size to 36 pixels.

4. Styling a Container:

  • The .container class is targeted for styling.
  • margin: 0 auto; centers the container horizontally using automatic left and right margins.
  • max-width: 1200px; sets the maximum width of the container to 1200 pixels.
  • padding: 20px; adds 20 pixels of padding around the container.

5. Styling Recipe List:

  • The .recipe-list class is targeted to style an unordered list (presumably a list of recipes).
  • list-style: none; removes the default bullet points from the list.
  • margin: 0; padding: 0; removes any margin and padding from the list.

6. Styling Recipe Items:

  • The .recipe-item class is targeted to style individual recipe items.
  • display: flex; makes the items flexible (enables flexbox layout).
  • align-items: center; justify-content: space-between; centers items vertically and distributes space evenly between them horizontally.
  • margin-bottom: 20px; adds a 20-pixel margin at the bottom.
  • box-shadow: ...; adds a subtle box shadow for a lifted appearance.
  • border-radius: 5px; rounds the corners of the recipe items.
  • overflow: hidden; hides any overflowing content.

7. Styling Recipe Item Image:

  • The .recipe-item img selector targets the images inside recipe items.
  • width: 150px; height: 150px; sets the width and height of the image.
  • object-fit: cover; scales the image while maintaining its aspect ratio, covering its container.

8. Styling Recipe Item Headings (h2) and Paragraphs (p):

  • .recipe-item h2 is styled with a font size of 20 pixels and some padding.
  • .recipe-item p has a font color of #777 (a dark gray).

9. Styling Recipe Item Links:

  • .recipe-item a styles the links within the recipe items.
  • background: #0c2461; color: #fff; sets background and text colors.
  • min-width: 150px; padding: 10px; sets minimum width and adds padding.
  • text-decoration: none; text-transform: uppercase; font-size: 14px; removes underlines, transforms text to uppercase, and sets font size.
  • transition: background 0.3s ease; adds a smooth transition effect on background changes.

10. Styling Hover Effects:

  • .recipe-item a:hover changes the background color on hover to create a visual feedback effect.

11. Media Query for Responsive Design:

  • Inside the @media query, styles are adjusted for screens with a maximum width of 768 pixels.
  • .container width is reduced for smaller screens.
  • .recipe-item flex direction changes to column layout.
  • Image width adjusts to 100% with auto height to maintain aspect ratio.
  • Various font sizes and spacings are adjusted for better readability on smaller screens.
  • Links are centered with full width.

This will give our recipe book an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.

body {
  margin: 0;
  padding: 0;
  font-family: Arial, sans-serif;
}

header {
  background: #0c2461;
  color: #fff;
  padding: 20px;
  text-align: center;
}

h1 {
  margin: 0;
  font-size: 36px;
}

.container {
  margin: 0 auto;
  max-width: 1200px;
  padding: 20px;
}

.recipe-list {
  list-style: none;
  margin: 0;
  padding: 0;
}

.recipe-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
  border-radius: 5px;
  overflow: hidden;
}

.recipe-item img {
  width: 150px;
  height: 150px;
  object-fit: cover;
}

.recipe-item h2 {
  margin: 0;
  font-size: 20px;
  padding: 10px;
  min-width: 200px;
}

.recipe-item p {
  margin: 0;
  padding: 10px;
  color: #777;
}

.recipe-item a {
  background: #0c2461;
  color: #fff;
  min-width: 150px;
  padding: 10px;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 14px;
  transition: background 0.3s ease;
}

.recipe-item a:hover {
  background: #1e3799;
}

@media screen and (max-width: 768px) {
  .container {
    max-width: 90%;
  }
  .recipe-item {
    flex-direction: column;
  }

  .recipe-item img {
    width: 100%;
    height: auto;
    margin-bottom: 10px;
  }

  .recipe-item h2 {
    font-size: 20px;
    padding: 0;
    margin-bottom: 10px;
  }

  .recipe-item p {
    font-size: 14px;
    margin-bottom: 10px;
  }

  .recipe-item a {
    width: 100%;
    text-align: center;
  }
} 

Step 3 (JavaScript Code):

Finally, we need to create a function in JavaScript. This JavaScript code is responsible for fetching random recipes using the Spoonacular API and displaying them on a web page. Let's break down the code step by step:

1. API_KEY: This constant holds the API key required to access the Spoonacular API. API keys are typically used for authentication and authorization when making requests to external APIs.

2. recipeListEl: This variable stores a reference to an HTML element with the id "recipe-list". This is where the list of recipes will be displayed on the webpage.

3. displayRecipes(recipes): This function takes an array of recipe objects as a parameter and displays them on the webpage. It does this by first clearing the content of the "recipe-list" element. Then, for each recipe in the array, it creates HTML elements to represent the recipe's image, title, ingredients, and a link to view the full recipe. These elements are structured and nested in the appropriate way to create a visual representation of each recipe. Finally, the assembled recipe item element is added to the "recipe-list" element.

4. getRecipes(): This asynchronous function makes a request to the Spoonacular API to fetch random recipes. It uses the fetch function to send a request to the specified API endpoint, which includes the API key and the number of recipes to fetch. After receiving a response, it extracts the JSON data and returns an array of recipe objects.

5. init(): This asynchronous function serves as the initialization point for the application. It first calls the getRecipes() function to fetch an array of random recipes. Then, it calls the displayRecipes() function to display those recipes on the webpage.

6. init() (last line): This line of code invokes the init() function, starting the process of fetching recipes and displaying them on the webpage. This is the entry point of the script.

Create a JavaScript file with the name of script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document, so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.

const API_KEY = "92f0263949a74da9877e2fb48b92fbf9";
const recipeListEl = document.getElementById("recipe-list");

function displayRecipes(recipes) {
  recipeListEl.innerHTML = "";
  recipes.forEach((recipe) => {
    const recipeItemEl = document.createElement("li");
    recipeItemEl.classList.add("recipe-item");
    recipeImageEl = document.createElement("img");
    recipeImageEl.src = recipe.image;
    recipeImageEl.alt = "recipe image";

    recipeTitleEl = document.createElement("h2");
    recipeTitleEl.innerText = recipe.title;

    recipeIngredientsEl = document.createElement("p");
    recipeIngredientsEl.innerHTML = `
        <strong>Ingredients:</strong> ${recipe.extendedIngredients
          .map((ingredient) => ingredient.original)
          .join(", ")}
    `;

    recipeLinkEl = document.createElement("a");
    recipeLinkEl.href = recipe.sourceUrl;
    recipeLinkEl.innerText = "View Recipe";

    recipeItemEl.appendChild(recipeImageEl);
    recipeItemEl.appendChild(recipeTitleEl);
    recipeItemEl.appendChild(recipeIngredientsEl);
    recipeItemEl.appendChild(recipeLinkEl);
    recipeListEl.appendChild(recipeItemEl);
  });
}

async function getRecipes() {
  const response = await fetch(
    `https://api.spoonacular.com/recipes/random?number=6&apiKey=${API_KEY}`
  );

  const data = await response.json();

  return data.recipes;
}

async function init() {
  const recipes = await getRecipes();
  displayRecipes(recipes);
}

init();

Final Output:

Creating a Recipe Book App Using HTML, CSS, and JavaScript.gif

See the Pen Recipe Book App by Faraz (@codewithfaraz) on CodePen.

Conclusion:

As we end this culinary coding adventure, it's time to savor the fruits of your labor – your very own digital recipe book that seamlessly marries the worlds of cooking and coding. You've embarked on a journey that has taken you from the realms of HTML and CSS design to the dynamic interactivity of JavaScript, all the way to the integration of a Food & Recipe API that has infused your creation with a world of gastronomic diversity.

Through each step, you've gained invaluable insights into how these technologies work together to create an engaging and functional platform. Your recipe book isn't just a compilation of recipes; it's a testament to your creativity, dedication, and newfound skills. Every recipe card designed, every interactive element coded, and every API call integrated has contributed to a harmonious symphony of flavors and functions.

By now, you've experienced the joy of flipping through virtual recipe cards, watching animations bring instructions to life, and exploring a treasure trove of culinary possibilities offered by the Food & Recipe API. But this is just the beginning. Your digital recipe book has the potential to keep growing, evolving, and inspiring. Imagine the smiles it will bring as users discover new dishes to try, new techniques to master, and new memories to create in their own kitchens.

As you reflect on your journey, remember that this tutorial was more than just a technical walkthrough. It was an invitation to merge your passions, embrace creativity, and share your love for both coding and cooking with the world. Your recipe book isn't just a collection of data; it reflects your unique blend of interests and skills.

So, as you prepare to close this chapter, keep your recipe book alive and thriving. Experiment with new designs, refine your code, and explore the endless possibilities technology offers to the culinary realm. Your creation has the power to inspire others to embark on their own culinary coding journeys, explore uncharted territories, and savor the magic that happens when flavors and code intertwine.

As you continue to explore the vast landscape of technology and gastronomy, remember that this is just one recipe – one combination of ingredients that has produced a delightful outcome. Keep seeking, keep experimenting, and keep pushing the boundaries of what's possible. Your digital recipe book is a testament to your potential to create, innovate, and inspire. Happy coding!

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post