15 Web Projects With Vanilla JavaScript Build 15 Mini Frontend Projects From Scratch With HTML5, CSS JavaScript (Alam, Asadullah)
15 Web Projects With Vanilla JavaScript Build 15 Mini Frontend Projects From Scratch With HTML5, CSS JavaScript (Alam, Asadullah)
Section 1: Introduction
Chapter 1: Welcome To The Course
Chapter 2: Getting Setup
Section 2: Project 1 - Form Validator | Intro Project
Chapter 3: Project Intro
Chapter 4: Project HTML
Chapter 5: Project CSS
Chapter 6: Adding Simple Validation
Chapter 7: Check Required & Refactor
Chapter 8: Check Length, Email & Password Match
Section 3: Project 2 - Movie Seat Booking | DOM &
Local Storage
Chapter 9: Project Intro
Chapter 10: Project HTML
Chapter 11: Project CSS
Chapter 12: Selecting Movie & Seats From UI
Chapter 13: Save Data To Local Storage
Chapter 14: Populate UI With Saved Data
Section 4: Project 3 - Custom Video Player | HTML5
Video API
Chapter 15: Project Intro
Chapter 16: Project HTML
Chapter 17: Project CSS
Chapter 18: Play, Pause & Stop
Chapter 19: Video Progress Bar & Timestamp
Section 5: Project 4 - Exchange Rate Calculator |
Fetch & JSON Intro
Chapter 20: Project Intro
Chapter 21: Project HTML
Chapter 22: Project CSS
Chapter 23: A Look at JSON & Fetch
Chapter 24: Fetch Rates & Update DOM
Section 6: Project 5 - DOM Array Methods | forEach,
map, filter, sort, reduce
Chapter 25: Project Intro
Chapter 26: Project UI
Chapter 27: Generate Random Users - Fetch w/
Async/Await
Chapter 28: Output Users - forEach() & DOM Methods
Chapter 29: Double Money - map()
Chapter 30: Sort By Richest - sort()
Chapter 31: Show Millionaires - filter()
Chapter 32: Calculate Wealth - reduce()
Section 7: Project 6 - Menu Slider & Modal | DOM &
CSS
Chapter 33: Project Intro
Chapter 34: Project HTML
Chapter 35: Navbar Styling
Chapter 36: Header & Modal Styling
Chapter 37: Menu & Modal Toggle
Section 8: Project 7 - Hangman Game | DOM, SVG,
Events
Chapter 38: Project Intro
Chapter 39: Draw Hangman With SVG
Chapter 40: Main Styling
Chapter 41: Popup & Notification Styling
Chapter 42: Display Words Function
Chapter 43: Letter Press Event Handler
Chapter 44: Wrong Letters & Play Again
Section 9: Project 8 - Meal Finder | Fetch & MealDB
API
Chapter 45: Project Intro
Chapter 46: Project HTML & Base CSS
Chapter 47: Search & Display Meals From API
Chapter 48: Show Single Meal Page
Chapter 49: Display Random Meal & Single Meal CSS
Section 10: Project 9 - Expense Tracker | Array
Methods & Local Storage
Chapter 50: Project Intro
Chapter 51: Project HTML
Chapter 52: Project CSS
Chapter 53: Show Transaction Items
Chapter 54: Display Balance, Income & Expense
Chapter 55: Add & Delete Transactions
Chapter 56: Persist To Local Storage
Section 11: Project 10 - Infinite Scroll Posts | Fetch,
Async/Await, CSS Loader
Chapter 57: Project Intro
Chapter 58: Project HTML
Chapter 59: Project CSS & Loader Animation
Chapter 60: Get Initial Posts From API
Chapter 61: Add Infinite Scrolling
Chapter 62: Filter Fetched Posts
Section 12: Project 11 - Speech Text Reader | Speech
Synthesis
Chapter 63: Project Intro
Chapter 64: HTML & Output Speech Boxes
Chapter 65: Project CSS
Chapter 66: Get Speech Voices
Chapter 67: Speech Buttons
Chapter 68: Change Voice & Custom Text Box
Section 13: Project 12 - Relaxer App | CSS
Animations, setTimeout
Chapter 69: Project Intro
Chapter 70: Creating The Large Circle
Chapter 71: Creating & Animating The Pointer
Chapter 72: Breath Animation With JS Trigger
Section 14: Project 13 - New Year Countdown | DOM,
Date & Time
Chapter 73: Project Intro
Chapter 74: Landing Page HTML & Styling
Chapter 75: Create The Countdown
Chapter 76: Dynamic Year & Spinner
Section 15: Project 14 - Sortable List | Drag & Drop
API
Chapter 77: Project Intro
Chapter 78: Insert List Items Into DOM
Chapter 79: Scramble List Items
Chapter 80: Core CSS
Chapter 81: Drag & Drop Functionality
Chapter 82: Check Order
Section 16: Project 15 - Breakout Game | HTML5
Canvas API
Chapter 83: Project Intro
Chapter 84: Creating & Styling The Page
Chapter 85: Canvas Plan Outline
Chapter 86: Draw Ball, Paddle & Score
Chapter 87: Creating The Bricks
Chapter 88: Move Paddle
Chapter 89: Move Ball & Break Bricks
Chapter 90: Lose & Reset Game
~ Conclusion
Section 1:
Introduction
Welcome To The Course
First and foremost, let me express my sincere gratitude
for picking up “15 Web Projects With Vanilla JavaScript.”
This coursebook is your gateway to stepping into the
world of web development, where you’ll be sculpting
projects using the fundamental tools of the web: HTML5,
CSS, and JavaScript. As you turn the pages of this
coursebook, you will embark on an immersive journey,
one that promises not only to equip you with the
necessary skills but also to offer an engaging hands-on
experience.
Prerequisites
While this coursebook is designed to be comprehensive,
having a foundational understanding of HTML, CSS, and
JS will be beneficial. If you’re an absolute beginner, I’d
recommend starting with my “Modern HTML/CSS From
The Beginning” and “Modern JS From The Beginning”
courses on Udemy. This will give you a solid footing to
tackle the projects in this coursebook.
Wrapping Up
Remember, every coder, no matter how skilled, started
from scratch. With patience, persistence, and the right
resources, you too can carve out your niche in the world
of web development.
So, as we stand at the threshold of this exciting journey,
take a deep breath, roll up your sleeves, and let’s dive
into the world of web projects with vanilla JavaScript!
Ge ng Setup
Welcome to the first step of our exciting journey through
the world of web development! Before diving into the
various projects we’ll tackle, it’s essential to ensure our
development environment is correctly set up. This
chapter will guide you through the installation and
configuration of all the tools and software required to
follow along with the projects in this book.
2.8. Wrapping Up
Congratulations! You’ve set up your development
environment. As you proceed through the book, you’ll
gain hands-on experience and deepen your
understanding of the tools we’ve discussed in this
chapter. Remember, web development is a journey, and
every project will enhance your skills and knowledge.
Now that we’re all set, let’s dive into our first project in
the next chapter!
Prerequisites
You should have a basic understanding of HTML, CSS,
and JavaScript. If you’re completely new or need a
refresher, it’s advisable to first check out the “Modern
HTML/CSS From The Beginning” and “Modern JS From
The Beginning” courses on Udemy.
Project HTML
Welcome to Chapter 4, where we’re going to dive into
the heart of our first project: the Form Validator. Before
we begin styling and adding dynamic functionality, we
need a solid foundation. That foundation is our HTML
structure.
Conclusion:
The HTML structure for our Form Validator is set up. As
simple as it might look now, this structure is the
backbone of our dynamic functionality.
Always remember, the key to creating effective web
projects is to maintain a clean and understandable
structure in the HTML, which makes styling and scripting
a lot smoother. Onward to the next chapter!
Project CSS
Welcome to the styling portion of our first project: the
Form Validator. As you may recall, the aim of this project
is to introduce you to the basics of web development,
and one of the essential aspects of building a visually
appealing web application is styling. CSS (Cascading
Style Sheets) allows us to apply styles to our HTML
documents, making them more aesthetically pleasing
and user-friendly.
For our form validator, we’re going to focus on creating a
neat, simple, and intuitive design that guides users
through the process of inputting their details. The goal
here is not just to make things look nice but also to use
styles as a tool for better usability.
1. Base Styles:
Let’s begin by adding some general styles to our form:
“`css
body {
font-family: Arial, sans-serif;
line-height: 1.6;
background-color: f4f4f4;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.container {
background-color: fff;
padding: 20px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
width: 400px;
}
“`
These base styles will provide a pleasant gray
background, center our form on the page, and give the
form container a nice shadow and rounded corners.
2. Form Styles:
Now, let’s style the form elements.
“`css
form {
width: 100%;
}
form label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
form input[type=“text”],
form input[type=“password”],
form input[type=“email”] {
width: 100%;
padding: 10px;
margin-bottom: 10px;
border: 1px solid ccc;
border-radius: 4px;
}
form button {
display: block;
width: 100%;
padding: 10px;
border: none;
border-radius: 4px;
background-color: 333;
color: fff;
cursor: pointer;
}
“`
These styles make our form inputs stretch to take up the
full width of the container, making it easier for users to
click into them. They also apply some padding for better
visual spacing and a neat appearance.
4. Responsive Design:
Considering the growing number of mobile users, our
form should be responsive:
“`css
@media screen and (max-width: 420px) {
.container {
width: 90%;
}
}
“`
This media query ensures that on smaller screens, our
form takes up most of the viewport width, leaving a small
margin on the sides.
Conclusion:
CSS is a powerful tool that goes beyond just making
things look good. With the styles we’ve added, our form
is now not only visually appealing but also user-friendly.
The visual cues from our validation feedback styles will
guide users through the form, making the entire process
intuitive and efficient.
HTML Structure:
“`html
<form id=“userForm”>
<input type=“text” id=“username”
placeholder=“Username”>
<input type=“email” id=“email” placeholder=“Email”>
<input type=“password” id=“password”
placeholder=“Password”>
<button type=“submit”>Submit</button>
<p id=“error-message”></p>
</form>
“`
The `error-message` paragraph is where we will display
any validation errors to the user.
JavaScript Validation:
Begin by selecting our form and adding an event listener
for the `submit` event.
“`javascript
const form = document.getElementById(‘userForm’);
form.addEventListener(‘submit’, function(e) {
e.preventDefault(); // Prevents the form from
submitting
validateForm();
});
“`
Conclusion
Checking required fields is a fundamental step in form
validation. With our `checkRequired` function, we can
now easily ensure that users have filled out all essential
fields. Moreover, by refactoring our code, we’ve made it
more efficient and maintainable. As we progress with our
form validator project, remember the importance of clean
code. It’s not just about getting it to work; it’s about
building something that’s robust and easy to understand.
In the next chapter, we will further enhance our validator
by adding checks for input length, email format, and
password match. Stay tuned!
Conclusion
By the end of this chapter, you’ve learned to implement
specific validation checks that are common in many web
applications. Ensuring the proper length, format, and
consistency of user input is essential for both usability
and security. As we progress through the course, you’ll
discover more advanced techniques to enhance your
form validation processes further.
Overview
Imagine a world where every time you wanted to watch a
movie, you’d simply load up your own app, select the
movie, choose your preferred seats, and voila! The app
would remember your choice, even if you accidentally
closed it. Sounds great, right? That’s precisely what
we’re building in this project.
Key Features
1. Dynamic Movie Selection: Display a list of movies with
their prices and allow users to choose one.
2. Interactive Seat Map: A graphical representation of
the movie theater, where users can click on individual
seats to select or deselect them.
3. Seat Booking: Allow users to book their desired seats
by clicking on them. Booked seats will have a different
color or style to distinguish them from available seats.
4. Price Calculation: Display the total price based on the
number of seats selected and the price of the chosen
movie.
5. Local Storage Capabilities: Save the user’s movie and
seat selection even if they close the browser. When they
revisit, their choices should still be there.
Real-World Applications
Beyond just being a fun project, understanding these
concepts is crucial for building interactive web
applications.
- E-commerce sites use similar techniques for shopping
carts, ensuring that your selected items remain in the
cart even after navigating away.
- Forms on many websites remember your input if you
navigate away and come back, enhancing user
experience.
By mastering these concepts here, you’ll be well-
equipped to tackle real-world challenges in web
development.
Prerequisites
Before diving into this project, it would be beneficial to
have:
1. A basic understanding of HTML, CSS, and JavaScript.
If you’re new to these, refer back to our foundational
chapters or courses.
2. Familiarity with the basics of the DOM, particularly
how to select and modify elements.
Conclusion
This project is an exciting blend of front-end design with
backend-like functionalities using pure front-end
technologies. Not only will it boost your confidence in
building real-world projects, but it will also be an
excellent addition to your portfolio, showcasing your
prowess in DOM manipulation and Local Storage.
Project HTML
Welcome to the heart of our second project: the Movie
Seat Booking application. This project will give you
practical experience working with the Document Object
Model (DOM) and the Local Storage of a browser. But
before we delve into the interactive JavaScript and CSS
styling, we need to lay the groundwork with our HTML.
This is where it all starts.
5. Information Display
Beneath the cinema layout, we’ll provide an area to
display information to the user:
“`html
<div class=“info”>
<p>Total Tickets: <span id=“ticketCount”>0</span>
</p>
<p>Total Price: $<span id=“totalPrice”>0</span></p>
</div>
“`
The information display shows the number of tickets and
the total price.
6. Conclusion
This sets the foundation for our movie seat booking app.
With the HTML in place, we’ll be diving into the CSS to
make our app visually appealing in the next chapter,
followed by the JavaScript to give it dynamic
functionality.
Remember, a well-structured HTML will simplify the
process when it comes to styling and adding interactivity.
Think of this as building the skeleton of our application,
upon which we’ll layer on the muscles (CSS) and the
brain (JavaScript).
In the next chapter, we’ll delve into the styling of this
project. Make sure your HTML structure aligns with what
we’ve covered here, as it will be crucial for our CSS and
JavaScript to function correctly.
Project CSS
In this chapter, we’ll be diving deep into styling our Movie
Seat Booking App using pure CSS. Our goal is to create
an intuitive, engaging, and aesthetically pleasing user
interface that aligns well with the functionality we will
develop in the subsequent chapters.
CSS Structure:
We will break down our styles into three main parts:
1. Base Styles: This is where we set up our foundational
styles such as the app’s font, colors, and general layout.
2. Component Styles: These will include styles for
specific components like buttons, seat selections, and
movie dropdown.
3. Utility Styles: General utility styles that might be
reused.
1. Base Styles
HTML Body and Container:
“`css
body {
font-family: ‘Arial’, sans-serif;
background-color: f4f4f4;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.container {
background-color: fff;
padding: 20px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
width: 80%;
max-width: 800px;
}
“`
Default Text Styles:
“`css
h1, h2, h3 {
margin-top: 0;
}
p{
margin-bottom: 20px;
}
“`
2. Component Styles
Movie Dropdown:
“`css
.movie-select {
display: flex;
justify-content: space-between;
margin: 20px 0;
}
.movie-select select {
padding: 10px 15px;
border-radius: 5px;
border: 1px solid e0e0e0;
}
“`
Seats in Cinema:
To visualize the cinema, we will use a flexbox to position
the seats and the screen.
“`css
.cinema {
perspective: 1000px;
}
.screen {
background-color: d3d3d3;
height: 70px;
width: 100%;
margin: 20px 0;
text-align: center;
line-height: 70px;
font-size: 1.5em;
letter-spacing: 3px;
}
.seats {
display: flex;
flex-direction: row;
flex-wrap: wrap;
position: relative;
}
.seat {
background-color: BDC3C7;
width: 20px;
height: 20px;
margin: 5px;
border-top-left-radius: 10px;
border-top-right-radius: 10px;
cursor: pointer;
}
.seat.occupied {
background-color: E74C3C;
cursor: not-allowed;
}
.seat.selected {
background-color: 2ECC71;
}
“`
Summary and Button Styles:
“`css
.summary {
margin-top: 20px;
display: flex;
justify-content: space-between;
}
button {
padding: 10px 20px;
border: none;
border-radius: 5px;
background-color: 2ECC71;
color: ffffff;
cursor: pointer;
transition: background-color 0.3s;
}
button:hover {
background-color: 27AE60;
}
“`
3. Utility Styles
“`css
.clearfix::after {
content: ””;
clear: both;
display: table;
}
“`
Conclusion
Styling is an integral part of any web application, and as
we’ve seen in this chapter, it plays a pivotal role in the
user experience. With our CSS now set up, our Movie
Seat Booking application is not only functional but also
visually engaging.
Conclusion:
By now, you should have a functional UI that allows
users to select a movie, choose their preferred seats,
and view the total cost of their selection. In the next
chapter, we’ll look into saving these details into local
storage and populating the UI with saved data to
enhance the user experience.
Conclusion
Utilizing local storage in our Movie Seat Booking project
ensures a user-friendly experience. This feature is
especially crucial for scenarios where a user might
accidentally refresh or navigate away from the page.
With local storage, their seat and movie selections
remain, saving them from the hassle of reselecting.
In the next chapter, we will explore how to populate the
UI with the saved data from local storage, ensuring a
seamless experience for returning users.
4. Populate Seats
Now, let’s populate the seats based on the saved
selections:
“`javascript
const seats =
document.querySelectorAll(‘.seat:not(.occupied)’);
if (selectedSeats !== null && selectedSeats.length > 0) {
seats.forEach((seat, index) => {
if (selectedSeats.indexOf(index) > -1) {
seat.classList.add(‘selected’);
}
});
}
“`
In this code:
- We first select all the seats that are not occupied.
- We then check if `selectedSeats` contains data and
loop through each seat.
- If the seat’s index is found in the `selectedSeats` array,
we add the `selected` class to that seat, visually marking
it as selected.
6. Final Thoughts
It’s essential always to consider the user’s experience
when developing applications. By populating the UI with
saved data, we save the user time and provide a sense
of continuity, especially if they had to navigate away from
the page and then come back.
In the next section, we’ll dive into the custom video
player and how to harness the power of the HTML5
Video API. Stay tuned!
Project HTML
Welcome to the next exciting phase of our project series!
In this chapter, we’ll be laying the foundation for our
Custom Video Player project by setting up the HTML
structure. This player will leverage the HTML5 Video
API, giving us capabilities to play, pause, skip, and more.
But before any of that, we need to build our HTML
scaffold!
Conclusion:
Setting up the HTML is the first step in creating our
Custom Video Player. This structure provides a
foundation upon which we’ll build our styles and
functionalities. In the upcoming chapters, we will focus
on styling this structure with CSS and then implementing
the video controls with JavaScript. The goal is to create
a player that is both functional and aesthetically
pleasing, offering users an enhanced video playback
experience.
Project CSS
Welcome back! Now that we’ve set up the HTML
structure for our custom video player in the previous
chapter, it’s time to style it and give it an appealing look.
CSS is the backbone of web aesthetics. In this chapter,
we’ll focus on making our video player not just functional,
but also user-friendly and visually appealing.
1. Basic Reset:
To begin with, let’s reset some default styles. This will
help us maintain consistency across browsers.
“`css
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
“`
4. Video Controls:
Below the video, we’ll have our custom controls which
will include play/pause buttons, a progress bar, volume
control, and full-screen toggling.
“`css
.video-controls {
display: flex;
align-items: center;
justify-content: space-between;
background-color: 333;
color: fff;
padding: 10px 15px;
}
“`
4.1 Buttons:
All buttons will have a consistent style.
“`css
.video-controls button {
background: none;
border: none;
color: fff;
font-size: 16px;
margin-right: 15px;
cursor: pointer;
}
“`
For any active or hover state:
“`css
.video-controls button.active,
.video-controls button:hover {
color: ff6347;
}
“`
4.2 Progress Bar:
The progress bar will show how much of the video has
been played.
“`css
.progress-bar {
flex: 1;
height: 5px;
background-color: 555;
margin: 0 10px;
position: relative;
}
“`
For the played section:
“`css
.progress-bar span {
display: block;
height: 100%;
background-color: ff6347;
position: absolute;
left: 0;
top: 0;
width: 0%; /* This will be updated dynamically using
JavaScript */
}
“`
4.3 Volume Control:
“`css
.volume {
display: flex;
align-items: center;
}
.volume-slider {
width: 100px;
margin-left: 10px;
}
“`
Wrapping Up:
With the HTML5 Video API, implementing play, pause,
and stop functionality becomes a walk in the park. The
API offers a wide range of methods and properties that
can help developers create robust and feature-rich video
players.
In the next chapter, we’ll dive into enhancing our video
player’s user experience by adding a progress bar and a
timestamp, allowing users to visually see the playback
status and duration of the video.
Remember, practice makes perfect! Don’t hesitate to
play around with the code, try different functionalities,
and make this video player truly your own. Happy
coding!
2. HTML Structure
For our custom video player, let’s consider you already
have the following basic HTML structure from the
previous chapters:
“`html
<video id=“video” width=“750” controls>
<source src=“path_to_video.mp4” type=“video/mp4”>
</video>
<div id=“video-controls”>
<div id=“progress-bar”>
<div id=“progress”></div>
</div>
<span id=“timestamp”>00:00 / 00:00</span>
</div>
“`
Here, `progress-bar` is the container, and `progress` is
the fill that’ll show video playback progress. The
`timestamp` will display the current time and total video
duration.
4. JavaScript Functionality
Now, let’s dive into the fun part – the JavaScript!
a. Progress Bar
We want the progress bar to fill up as the video plays:
“`javascript
const video = document.getElementById(‘video’);
const progressBar =
document.getElementById(‘progress-bar’);
const progress = document.getElementById(‘progress’);
video.addEventListener(‘timeupdate’,
updateProgressBar);
function updateProgressBar() {
const percentage = (video.currentTime /
video.duration) * 100;
progress.style.width = `${percentage}%`;
}
“`
b. Timestamp
To update the timestamp:
“`javascript
const timestamp =
document.getElementById(‘timestamp’);
video.addEventListener(‘timeupdate’,
updateTimestamp);
function updateTimestamp() {
const minutesCurrent = Math.floor(video.currentTime
/ 60);
let secondsCurrent = Math.floor(video.currentTime %
60);
if (secondsCurrent < 10) {
secondsCurrent = ‘0’ + secondsCurrent;
}
const minutesDuration = Math.floor(video.duration /
60);
let secondsDuration = Math.floor(video.duration %
60);
if (secondsDuration < 10) {
secondsDuration = ‘0’ + secondsDuration;
}
timestamp.textContent =
`${minutesCurrent}:${secondsCurrent} /
${minutesDuration}:${secondsDuration}`;
}
“`
5. Seeking Functionality
Let’s add the ability for users to click on the progress bar
to seek to different parts of the video:
“`javascript
progressBar.addEventListener(‘click’, setVideoProgress);
function setVideoProgress(e) {
const clickPosition = e.offsetX;
const width = progressBar.offsetWidth;
const clickPercentage = (clickPosition / width);
video.currentTime = clickPercentage * video.duration;
}
“`
6. Recap
By now, you have a functional progress bar that fills up
as the video plays and a timestamp that updates in real-
time. The user can also click on the progress bar to seek
the video, enhancing user control and experience.
Section 5: Project 4 -
Exchange Rate Calculator |
Fetch & JSON Intro
Project Intro
Welcome to Project 4, the Exchange Rate Calculator! In
this project, we will embark on a journey to create a
utility tool that can be widely used in daily life. Whether
you’re traveling, investing, or just curious about the world
economy, an exchange rate calculator provides essential
information about currency values in different countries.
Objective:
By the end of this project, you will have built an
interactive web application that retrieves real-time
exchange rates for various currencies and performs
calculations to convert amounts between these
currencies. This will be done using pure vanilla
JavaScript, giving you a hands-on experience with the
Fetch API and JSON data manipulation.
Project Overview:
Here’s a sneak peek into what we will be developing:
1. User Interface: A sleek and intuitive design with
dropdowns for selecting currencies and an input for the
amount to convert.
2. Real-time Data: We’ll fetch real-time exchange rates
from a free API.
3. Conversion Logic: Convert input currency to the
desired output currency and display the result.
4. Error Handling: Implement proper error checking and
handling to ensure a seamless user experience.
Pre-requisites:
Before diving into the coding part, make sure you have a
basic understanding of:
- HTML: For creating the basic structure of our
application.
- CSS: To style our application and make it visually
appealing.
- JavaScript: Basics of variables, functions, and events.
If you’re a beginner or want a refresher, I’d recommend
revisiting the chapters on HTML, CSS, and introductory
JavaScript from this book or checking out my other
courses on Udemy.
Conclusion:
With a clear goal in mind and excitement in our hearts,
let’s get started on building this project! The subsequent
chapters will guide you step by step, from laying out the
HTML structure, styling it with CSS, to bringing it to life
with JavaScript. By the end, you’ll have a fully functional
Exchange Rate Calculator and a deeper understanding
of web development techniques.
Are you ready to dive deep into the world of Fetch and
JSON? Let’s begin!
Project HTML
In this chapter, we’re going to lay the foundation for our
Exchange Rate Calculator project. The HTML structure
will form the skeleton upon which we will later add styling
(CSS) and dynamic functionality (JavaScript). By the end
of this chapter, you will have a clear understanding of the
layout and elements that comprise our exchange rate
calculator.
Structure Overview
Our Exchange Rate Calculator will consist of:
- A title
- Two dropdown lists for selecting source and target
currencies
- Two input fields for entering and displaying the
conversion result
- A button to perform the conversion
- A section to display the current exchange rate between
the selected currencies
Conclusion
By the end of this chapter, we’ve set up the essential
structure for our Exchange Rate Calculator using pure
HTML. We’ve ensured that our structure is clear and
semantic, making it accessible and easy to style and
script in the upcoming chapters. In the next chapters,
we’ll look into styling this structure with CSS and then
adding the dynamic functionalities with JavaScript.
Project CSS
Welcome to Chapter 22, where we’re going to focus on
styling our Exchange Rate Calculator project. The design
will be clean, modern, and intuitive. Given the
importance of user experience in web applications, our
goal is to create a user-friendly interface that’s easy to
navigate.
5. Currency Dropdowns:
We’ll have two dropdowns for users to select currencies
they want to exchange between.
“`css
.select-group {
margin-bottom: 20px;
}
.select-group select {
width: 48%;
padding: 10px;
border: 1px solid bbb;
border-radius: 5px;
}
“`
7. Button Styling:
Our calculate button will trigger the exchange rate
calculation.
“`css
.calculate-btn {
width: 100%;
padding: 10px;
background-color: 0099cc;
border: none;
border-radius: 5px;
color: fff;
font-size: 1.2em;
cursor: pointer;
transition: background-color 0.3s ease;
}
.calculate-btn:hover {
background-color: 0077aa;
}
“`
8. Responsive Design:
We want our calculator to look good on both desktops
and mobile devices.
“`css
@media (max-width: 600px) {
.input-group, .select-group {
flex-direction: column;
}
.input-group label, .input-group input, .select-group
select {
width: 100%;
margin-bottom: 10px;
}
}
“`
Conclusion:
With this CSS setup, our Exchange Rate Calculator
should now have a sleek, modern look. This ensures that
not only does our application work efficiently, but it also
provides a pleasant user experience. Remember, CSS is
all about experimentation and creativity, so don’t hesitate
to adjust the styles to suit your personal design
preferences.
In the next chapter, we’ll dive into understanding JSON
and how to use the Fetch API to retrieve current
exchange rates. Stay tuned!
What is JSON?
JSON stands for JavaScript Object Notation. It’s a
lightweight data interchange format that is easy for
humans to read and write, and easy for machines to
parse and generate. JSON is a text format, independent
of any language, which makes it an ideal data format for
data exchange between a client and server, or between
different parts of an application.
A JSON object looks like this:
“`json
{
“name”: “John”,
“age”: 30,
“city”: “New York”
}
“`
Key Features of JSON:
1. Readability: JSON structures are straightforward,
making it easy for humans to read and write.
2. Universality: Most programming languages, including
JavaScript, have built-in support for JSON.
3. Flexibility: JSON can represent a wide variety of data
structures, including objects, arrays, and primitive data
types.
Conclusion
Understanding JSON and the Fetch API is essential for
modern web development. These tools allow us to
interact with servers, APIs, and other external data
sources seamlessly. As we build our Exchange Rate
Calculator, we’ll see these concepts in action, retrieving
real-world data and presenting it to our users. In the next
chapters, we’ll integrate this knowledge into our project,
setting the foundation for dynamic, data-driven web
applications.
2. Fetch API
The Fetch API provides a simple interface for making
network requests and handling responses. The primary
method for this is `fetch()`.
Basic Syntax:
“`javascript
fetch(url)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(“There was an error!”,
error));
“`
- `url`: The URL you want to fetch.
- The `fetch()` method returns a promise that resolves
into the Response object representing the response to
the request.
- The `response.json()` method reads the response body
and returns it as a JSON object.
6. Event Listeners
To make our application responsive to user actions, let’s
add event listeners:
“`javascript
currencyOne.addEventListener(‘change’, calculate);
currencyTwo.addEventListener(‘change’, calculate);
amountOne.addEventListener(‘input’, calculate);
amountTwo.addEventListener(‘input’, calculate);
“`
The `calculate` function will call our fetching logic and
update the DOM. Now, every time a user changes the
currency type or adjusts the amount, our application will
dynamically fetch the new rate and update the DOM.
7. Error Handling
The world of APIs isn’t always perfect. There can be
downtimes, or we might exceed our API request limits.
Let’s add some basic error handling:
“`javascript
fetch(apiURL)
.then(response => {
if(!response.ok) {
throw new Error(“Network response was not ok”);
}
return response.json();
})
.then(data => {
//… rest of the logic
})
.catch(error => {
console.error(“There was a problem with the fetch
operation:”, error.message);
});
“`
8. Conclusion
With this, our Exchange Rate Calculator’s core
functionality is complete! You’ve successfully
incorporated an external API into your project and made
your application dynamic and interactive.
In subsequent projects, you’ll explore more about
asynchronous JavaScript and how to further interact with
APIs and the DOM. Remember, practice is key. The
more projects you build, the more proficient you’ll
become.
Section 6:
Project 5 - DOM Array
Methods | forEach, map, filter,
sort, reduce
Project Intro
Welcome to Project 5: DOM Array Methods Exploration!
If you’ve ever been intrigued by the powerful capabilities
JavaScript offers when working with arrays, you’re in the
right place. This project will provide an insightful journey
into some of the most widely-used and fundamental
array methods in JavaScript.
Learning Outcomes
By the end of this project, you will:
1. Deepen Your Understanding of Array Methods: We’ll
delve deep into methods like `forEach`, `map`, `filter`,
`sort`, and `reduce`. You’ll understand not just how, but
also why and when to use them.
2. Enhance DOM Manipulation Skills: You’ll get a lot of
practice dynamically adding, removing, and altering
elements on a webpage.
3. Strengthen Async Operations: We’ll be fetching data
from an API, giving you a practical scenario to
understand asynchronous operations in JavaScript.
4. Boost Problem-Solving Abilities: Through hands-on
tasks, you’ll improve your logical thinking and problem-
solving skills.
Prerequisites
To make the most of this project:
- A basic understanding of HTML, CSS, and JavaScript
is required. If you’re a beginner, I’d recommend revisiting
the earlier chapters on these topics.
- An understanding of how to fetch data from APIs will be
beneficial. If you’re unfamiliar, don’t worry! We’ll cover
the basics in this project.
- Patience and a willingness to experiment. Sometimes,
the best way to understand a concept is to play around
with it, make mistakes, and learn from them.
A Word Before We Begin
Every developer, novice or expert, goes through a
journey of discovery and learning. This project is
designed as a stepping stone in your path to mastering
web development. While the focus is on array methods
and DOM manipulation, remember that the broader goal
is to nurture a mindset of exploration and continuous
learning.
Dive in with enthusiasm, keep an open mind, and most
importantly, enjoy the process! Let’s embark on this
exciting journey together.
Project UI
In the world of web development, the user interface (UI)
is the space where interactions between humans and
machines occur. The goal of this interaction is to allow
effective operation and control of the machine from the
human end, while the machine simultaneously provides
feedback that aids the operators’ decision-making
process. In “Project 5: DOM Array Methods”, our main
objective is to showcase an array of different JavaScript
methods, and to effectively do so, we need a fitting UI.
The purpose of this project is to build a dynamic user
dashboard that will list out random users, their wealth,
and provide us with various functionalities to manipulate
this data. The user will be able to double the money for
users, sort by the richest, filter to show only millionaires,
and calculate total wealth. Let’s get started with crafting
this UI!
Conclusion:
The UI plays a crucial role in ensuring our project’s array
methods are both understood and appreciated by the
end-user. By setting up a simple yet effective interface,
we pave the way for the logical JavaScript functions that
will populate and manipulate the data on this interface.
In the upcoming chapters, we’ll delve deeper into
fetching random user data, and employing the array
methods to provide the functionalities we’ve hinted at
with our action buttons. Stay tuned and keep coding!
Handling Errors
When working with APIs, it’s crucial to handle errors
gracefully. Network problems, API downtimes, or request
limits can cause issues. With `async/await`, we can use
simple try/catch blocks:
“`javascript
async function fetchMultipleUsers(num) {
try {
let response = await
fetch(`https://randomuser.me/api/?results=${num}`);
if (!response.ok) {
throw new Error(`HTTP error! Status:
${response.status}`);
}
let data = await response.json();
displayUsers(data.results);
} catch (error) {
console.error(‘Fetch error: ‘ + error.message);
}
}
“`
Conclusion
In this chapter, we learned how to generate random user
data using the Random User Generator API, integrated
with the Fetch API and Async/Await. This technique can
be instrumental when you want to create mock data for
your applications, especially during the development
phase.
Remember, always refer to the API’s documentation if
you wish to explore more features or if you run into any
issues. APIs are powerful tools, and mastering them can
elevate your projects significantly.
Prerequisites:
Before jumping into this chapter, make sure you have:
1. Basic understanding of JavaScript and its ES6 syntax.
2. Familiarity with the Document Object Model (DOM).
3. Completed Chapter 27 where we generated a list of
random users using Fetch with Async/Await.
Summary:
In this chapter, we learned how to use the `forEach()`
method in conjunction with DOM methods to output
users to our web page. This is a fundamental pattern in
web development – fetching data and then displaying it
to the user.
In the next chapter, we will enhance our project by
adding functionalities that allow users to double their
money using the `map()` method. Stay tuned!
What is map()?
The `map()` method is a higher-order function that
creates a new array populated with the results of calling
a provided function on every element in the calling array.
Unlike `forEach()`, which doesn’t return anything, `map()`
returns a new array without mutating the original array.
Basic Syntax:
“`javascript
const newArray = array.map(function(currentValue,
index, arr), thisValue);
“`
- `currentValue`: The current element being processed in
the array.
- `index` (optional): The index of the current element
being processed.
- `arr` (optional): The array on which map was called.
- `thisValue` (optional): Object to use as `this` when
executing the function.
Conclusion
The `map()` function is a powerful tool in your JavaScript
toolkit. It provides an easy, efficient, and functional way
to transform data in arrays. In this chapter, we leveraged
`map()` to double the money for each user in our array.
However, its applications are diverse, and as you
progress through different web projects, you’ll find
countless scenarios where `map()` will come in handy.
Syntax of `sort()`
“`javascript
array.sort([compareFunction])
“`
The `compareFunction` is optional, but crucial for our
task. This function should return:
- A negative value if `a` should be sorted before `b`
- A positive value if `a` should be sorted after `b`
- Zero if `a` and `b` are equal
Conclusion
The `sort()` method, though appearing simple, is an
essential tool in your JavaScript toolbox. With it, you’ve
successfully sorted users by their wealth, enriching the
functionality of your web application. This method’s true
strength lies in its flexibility—by defining our own
comparison functions, we can sort arrays in numerous,
customized ways.
Remember, web development isn’t just about knowing
the tools; it’s about understanding them and innovating
with how you use them. As you move forward, think
about other exciting ways you can utilize `sort()` in your
projects!
Practice Exercise
Try sorting the users in ascending order of their wealth.
How would you modify the compare function to achieve
this?
Syntax:
“`javascript
let newArray = arr.filter(callback(element[, index[, array]])
[, thisArg])
“`
Where:
- `callback`: Function is a predicate, which returns a
Boolean value. It tests each element and returns `true` to
keep the element, `false` otherwise.
- `element`: Current element being processed in the
array.
- `index` (optional): Index of the current element in the
array.
- `array` (optional): The array `filter()` was called upon.
- `thisArg` (optional): Object to use as `this` when
executing the callback.
Conclusion
The `filter()` method is powerful, allowing us to extract
subsets of data from our main dataset based on specific
criteria. In this chapter, we successfully isolated and
displayed our millionaire users. As you progress through
your JavaScript journey, you’ll find countless scenarios
where `filter()` becomes indispensable.
Introduction to `reduce()`
The `reduce()` method applies a function to an
accumulator and each element in an array (from left to
right) to reduce it to a single value. The accumulator
accumulates the callback’s return values. If no
initialValue is provided, the first element in the array will
be used as the accumulator, and the callback will start
from the second element.
Syntax:
“`javascript
array.reduce(callback(accumulator, currentValue[, index[,
array]])[, initialValue])
“`
Key Points:
- accumulator: This accumulates the callback’s return
values.
- currentValue: The current element being processed in
the array.
- index (optional): The index of the `currentValue`.
- array (optional): The array `reduce()` was called upon.
- initialValue (optional): Value to use as the first
argument to the first call of the callback.
Wrapping Up
The `reduce()` method offers a concise way to calculate
aggregate values from arrays. In this chapter, we used it
to calculate the total wealth from an array of users. But
the `reduce()` function’s applications don’t end here. You
can use it in numerous scenarios, like finding the
maximum value in an array, counting occurrences of
items, and more.
4. Pre-requisites
While this project is designed to be accessible for those
with a basic understanding of HTML, CSS, and
JavaScript, it will be beneficial if you’ve gone through the
prior projects in this course. We’ll be building upon
foundational concepts introduced in earlier chapters.
Project HTML
Welcome to the HTML section of our sixth project: the
Menu Slider & Modal! This is where we lay down the
foundation of our project. Remember, a good structure in
your HTML is crucial to making your CSS and JavaScript
integration easier and more efficient.
Introduction
HTML (HyperText Markup Language) is the backbone of
any web page. It provides the structure, while CSS styles
it and JavaScript brings it to life. In this chapter, we’ll
focus on creating a semantic and accessible structure for
our Menu Slider and Modal.
Wrapping Up
With the HTML structure set for the Menu Slider & Modal
project, you’re ready to move on to styling with CSS and
adding functionality with JavaScript. Always ensure your
HTML is clear and semantic, as this not only makes your
website more accessible but also eases the process of
styling and scripting.
In the next chapter, we will dive into styling our Navbar
and setting up the overall look of our project with CSS.
Navbar Styling
Welcome to Chapter 35, where we’ll be focusing on one
of the most fundamental components of a web
application’s UI: the Navbar. The navigation bar, or
navbar for short, typically contains links that help users
navigate through different sections or pages of a
website. Given its importance, styling the navbar is
crucial for both aesthetics and usability. Let’s dive into
how we can style our navbar for the “Menu Slider &
Modal” project.
6. Additional Touches
To further refine our navbar, consider adding transitions
or animations for a smoother user experience. For
instance:
“`css
.nav-menu li a {
transition: all 0.3s ease;
}
“`
This will ensure that changes to properties like color,
when hovering over the menu items, are gradual and
smooth.
Conclusion
With these styles, our navbar is not only functional but
also visually appealing. A well-styled navbar enhances
user experience and guides them seamlessly through
your application. As always, feel free to adjust colors,
sizes, and other properties to better fit the overall design
and theme of your website.
In the next chapter, we’ll explore styling the header and
modal components, diving deeper into the world of CSS
and improving our project’s look and feel. Stay tuned!
Conclusion
With the header and modal now styled, our project is
starting to take shape. Styling plays a vital role in
dictating the feel and atmosphere of an application, and
by now, you should have a better understanding of how
to achieve this using pure CSS.
In the next chapter, we’ll delve into the JavaScript behind
the Menu and Modal Toggle functionalities, bringing our
project to life!
Conclusion:
By the end of this chapter, you’ve learned how to use
JavaScript and CSS in tandem to create a toggle
mechanism for a menu and a modal. By integrating this
knowledge into your web projects, you can create a
more interactive and dynamic user interface.
Section 8: Project 7 -
Hangman Game | DOM, SVG,
Events
Project Intro
Welcome to our seventh project - The Hangman Game!
This classic word game not only tests your vocabulary
but also provides a delightful user experience with the
help of SVG for graphics, DOM for dynamic content
manipulation, and JavaScript events to capture user
inputs. By the end of this project, you’ll have a fully
functional Hangman game that you can show off to your
friends or even include in your web portfolio.
Prerequisites:
While this is a standalone project, it’s beneficial if you
have a basic understanding of HTML, CSS, and
JavaScript, as we’ll dive deep into some advanced
topics. If you’re entirely new, I recommend going through
the previous sections of this book to build a solid
foundation.
Conclusion
Drawing with SVG provides immense flexibility when
creating graphics for web applications. In this chapter,
we explored how to use SVG to dynamically draw the
hangman figure for our game. By integrating SVG with
JavaScript, we can make our game more interactive and
responsive to player actions. As you progress with the
Hangman game project, you’ll appreciate the power and
flexibility SVG brings to web development.
Main Styling
Welcome to Chapter 40 of our journey through creating a
Hangman game. Now that we have a sketch of our
hangman using SVG, it’s time to give our game a visual
appeal that is inviting and intuitive. We’ll cover the main
styling for our Hangman game, focusing on creating an
engaging user experience.
3. Word Placeholder
The word that players are guessing will be displayed with
underscores for each unguessed letter. We’ll style these
so they’re easy to read and spaced nicely.
“`css
.word {
display: flex;
justify-content: center;
align-items: center;
height: 50px;
margin-bottom: 20px;
}
.letter, .placeholder {
margin: 0 5px;
font-size: 2em;
font-weight: bold;
display: inline-block;
width: 30px;
border-bottom: 2px solid 333;
text-align: center;
}
“`
4. Keyboard
For our game, players will select letters from an on-
screen keyboard. Let’s style these buttons:
“`css
.keyboard {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.key {
margin: 5px;
padding: 10px 15px;
border: none;
background-color: f4f4f4;
cursor: pointer;
border-radius: 4px;
transition: background-color 0.2s ease;
}
.key:hover {
background-color: ddd;
}
“`
5. Notification Pop-up
We’ll use a pop-up to notify players when they select a
repeated letter.
“`css
.notification {
position: absolute;
top: 10px;
right: 10px;
background-color: e74c3c;
color: fff;
padding: 10px 20px;
border-radius: 4px;
visibility: hidden;
opacity: 0;
transition: opacity 0.3s ease, visibility 0.3s ease;
}
.show-notification {
visibility: visible;
opacity: 1;
}
“`
6. Responsiveness
Finally, let’s ensure our game looks good on smaller
screens.
“`css
@media screen and (max-width: 768px) {
.hangman-board {
flex-direction: column;
}
.hangman-figure, .word, .keyboard {
width: 100%;
text-align: center;
}
}
“`
With these styles in place, our Hangman game should
now have a polished and user-friendly interface. In the
next chapter, we will dive into creating pop-ups and
notifications to guide our player through the game. Stay
tuned!
2. HTML Structure
Before styling, we need a proper HTML structure in
place. For simplicity, we’ll create a basic modal for both
our popup and notification.
“`html
<!— Popup Modal —>
<div class=“popup-modal”>
<div class=“popup-content”>
<span class=“close-btn”>×</span>
<h2>Game Over!</h2>
<p>You guessed the word correctly!
Congratulations!</p>
</div>
</div>
<!— Notification Modal —>
<div class=“notification-modal”>
<p>You’ve already chosen this letter. Try another
one!</p>
</div>
“`
3. Styling with CSS
Now, let’s make these popups and notifications visually
appealing and in line with the theme of our game.
Popup Modal Styling:
“`css
.popup-modal {
display: none; /* Hidden by default */
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.7); /* Semi-black
background */
z-index: 1; /* Ensure it appears on top */
}
.popup-content {
background-color: fefefe;
margin: 15% auto; /* Centered vertically */
padding: 20px;
border-radius: 10px;
width: 70%;
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
}
.close-btn {
color: aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close-btn:hover,
.close-btn:focus {
color: 000;
text-decoration: none;
cursor: pointer;
}
“`
Conclusion
And that wraps up our chapter on styling popups and
notifications! With these elements in place, our Hangman
Game will now be able to provide timely and visually
appealing feedback to the player. Remember, the user
experience is just as important as the core game logic. In
our next chapter, we’ll delve deeper into the game
mechanics with “Display Words Function”. Stay tuned!
6. Final Touches
To initialize our game, let’s call the
`displayWordsFunction()` when the game starts or
resets:
“`javascript
function startGame() {
selectedWord = getRandomWord();
displayWordsFunction();
// any other game initialization code…
}
“`
Conclusion
Our `Display Words Function` is the cornerstone of our
Hangman game. It selects a random word, masks it for
the player, and reveals the letters as they are guessed
correctly. Coupled with the game’s logic and user
interface, it forms an engaging experience for players. In
the subsequent chapters, we will delve into handling
user input and adding more features to our game.
Conclusion
The Letter Press Event Handler is crucial in allowing
interaction in our Hangman game. It helps capture user
input and makes the game responsive and dynamic. By
understanding how event handlers work in JavaScript
and how to effectively bind and handle them, you’ve
taken a significant step in enhancing user interactivity in
web applications.
Remember, while our focus was on the Hangman game,
the principles of event handling are universally
applicable in JavaScript and are key to creating
interactive web applications.
In the next chapter, we’ll explore how to handle wrong
guesses, update the display to draw parts of the
hangman, and offer players a chance to play again once
the game concludes. Stay tuned!
4. Wrapping Up
With these functionalities in place, the Hangman game
becomes interactive and user-friendly. Handling wrong
letter choices appropriately and providing feedback
improves the user experience, while the Play Again
option keeps players engaged.
Overview
In this project, we’ll be developing a Meal Finder
application, where users can search for meals, get a list
of matching results, view a single meal’s details, and
even receive a random meal suggestion. All of this will
be powered by the MealDB API, a free-to-use database
containing meal recipes and details.
Challenges Ahead
1. Handling API Responses: Not every search query will
return results. Learning how to handle such scenarios
gracefully enhances the user experience.
2. Dynamic DOM Manipulation: Based on the data
fetched, our application’s appearance will change
dynamically.
3. Error Handling: APIs can sometimes fail, or there
might be issues with connectivity. Proper error handling
ensures that our application is robust and user-friendly.
In the following chapters, we’ll delve into the nitty-gritty
details of building the Meal Finder application. From
setting up the basic structure in HTML to styling our
components with CSS and finally bringing everything to
life with JavaScript. So, roll up your sleeves and let’s get
cooking!
Note: Always refer to the MealDB API documentation
while working on this project. It provides valuable
insights into request endpoints, response formats, and
more. Always respect the API usage guidelines and
terms of service.
Summary
At this stage, our ‘Meal Finder’ project now has a basic
layout. With our structured HTML and base CSS styling,
we have a clean and intuitive interface ready. In the next
chapters, we will integrate the functionality to search for
meals using the MealDB API, display the results in our
app, and allow users to view detailed information about
each meal.
Conclusion
By now, you should have a functional Meal Finder that
allows users to search for meals using the MealDB API.
The results are displayed dynamically, and users can
view detailed recipes with just a click. Remember, APIs
offer a plethora of data that can be used to enhance your
web applications. The key lies in understanding the API
documentation, structuring your fetch requests
appropriately, and presenting the data to users in a user-
friendly manner.
Objective:
- Fetch detailed data for a single meal using the MealDB
API.
- Display the meal details including image, name,
category, origin, ingredients, and preparation steps.
Getting Started:
To show the single meal page, we will be utilizing the
`idMeal` property which is unique to each meal and can
be used to fetch the detailed information of that meal
from the MealDB API.
1. HTML Structure:
Let’s first design the layout for our single meal page.
“`html
<div class=“single-meal”>
<div class=“single-meal-header”>
<img src=”” alt=“Meal Image” id=“meal-img”>
<h2 id=“meal-name”></h2>
</div>
<div class=“single-meal-info”>
<p><strong>Category:</strong> <span id=“meal-
category”></span></p>
<p><strong>Origin:</strong> <span id=“meal-
origin”></span></p>
</div>
<div class=“single-meal-ingredients”>
<h3>Ingredients:</h3>
<ul id=“ingredients-list”></ul>
</div>
<div class=“single-meal-instructions”>
<h3>Instructions:</h3>
<p id=“meal-instructions”></p>
</div>
</div>
“`
2. CSS Styling:
For a better presentation, add some CSS for the single
meal display.
“`css
.single-meal-header {
display: flex;
align-items: center;
}
meal-img {
width: 150px;
height: 150px;
margin-right: 20px;
object-fit: cover;
border-radius: 50%;
}
.single-meal-info {
margin-top: 20px;
}
.single-meal-ingredients, .single-meal-instructions {
margin-top: 30px;
}
“`
3. JavaScript Functionality:
We will fetch and display the single meal’s details using
JavaScript.
“`javascript
function getSingleMealDetails(mealID) {
fetch(`https://www.themealdb.com/api/json/v1/1/looku
p.php?i=${mealID}`)
.then(response => response.json())
.then(data => {
const meal = data.meals[0];
displayMealDetails(meal);
})
.catch(error => console.error(‘Error fetching single
meal:’, error));
}
function displayMealDetails(meal) {
// Clear previous data
document.getElementById(‘meal-img’).src =
meal.strMealThumb;
document.getElementById(‘meal-name’).textContent
= meal.strMeal;
document.getElementById(‘meal-
category’).textContent = meal.strCategory;
document.getElementById(‘meal-origin’).textContent
= meal.strArea;
// List ingredients
const ingredientsList =
document.getElementById(‘ingredients-list’);
ingredientsList.innerHTML = ”;
for(let i = 1; i <= 20; i++) {
if(meal[`strIngredient${i}`]) {
const li = document.createElement(‘li’);
li.textContent = `${meal[`strIngredient${i}`]} -
${meal[`strMeasure${i}`]}`;
ingredientsList.appendChild(li);
}
}
// Display instructions
document.getElementById(‘meal-
instructions’).textContent = meal.strInstructions;
}
“`
4. Event Handling:
When a user clicks on a meal from the list, fetch its
details:
“`javascript
document.body.addEventListener(‘click’, (e) => {
if (e.target.classList.contains(‘meal-item’)) {
const mealID = e.target.getAttribute(‘data-mealid’);
getSingleMealDetails(mealID);
}
});
“`
Make sure that each meal displayed in the list has the
class `meal-item` and a `data-mealid` attribute with the
meal’s unique ID.
Wrapping Up:
You’ve successfully created a single meal page that
fetches detailed information about a meal and displays it
in a user-friendly format. Now, when users are intrigued
by a meal’s name or picture, they can dive deeper into
its ingredients and instructions.
In the next chapter, we will delve into how to display
random meals and style their presentation. Stay tuned!
Conclusion
With the above CSS, we’ve successfully enhanced the
visual representation of our random and single meal
displays. A well-structured and visually appealing design
will not only make our application look professional but
also provide a pleasant experience for our users.
Section 10:
Project 9 - Expense Tracker |
Array Methods & Local
Storage
Project Intro
As we journey through the vast world of web
development, we’ve seen how the amalgamation of
HTML, CSS, and JavaScript can give life to a variety of
dynamic applications. From form validation to creating
interactive movie seat bookings, every project has added
a new feather to your web development cap. In this
project, we’ll delve into an essential tool that many
individuals use daily - an Expense Tracker. By the end of
this project, you’ll have built a dynamic application that
not only tracks expenses and income but also persists
data using local storage.
Project Overview
In today’s digital age, where the proliferation of mobile
applications has taken center stage, expense tracking
applications have seen a massive rise in popularity. They
help users monitor their spending habits, keep track of
savings, and provide insights into their financial health.
With the Expense Tracker project, we aim to equip you
with the skills to build your own version of this handy
tool.
The primary objective of our Expense Tracker is:
- To record and display transactions (both expenses and
income).
- To display the current balance, total income, and total
expenditure.
- To provide functionalities to add and delete
transactions.
- To store transaction data in the local storage, ensuring
data persistence even after refreshing the page.
Conclusion
Brace yourself for an exhilarating journey as we navigate
through the intricacies of building an Expense Tracker.
By the end of this project, you’ll have a functional tool at
your disposal and a bolstered understanding of how to
build practical applications from scratch.
Now, let’s dive into the HTML structure in the next
chapter, setting the foundation for our Expense Tracker!
Project HTML
Welcome to the first technical step in building our
Expense Tracker! HTML is the backbone of any web
application. This chapter will help you structure the
Expense Tracker, ensuring that all the following steps in
CSS and JavaScript can be implemented seamlessly.
1. Introduction
In this chapter, we’ll lay out the basic HTML structure for
our Expense Tracker application. This will include areas
to display the balance, income, expenses, a list of
transactions, and a form to add new transactions. The
goal is to ensure the markup is semantic, accessible,
and easy to style.
3. Main Container
Let’s start by creating the main container for our
application.
“`html
<div class=“container”>
<!— All other components will go here —>
</div>
“`
6. Transaction History
This section will display the list of transactions added by
the user.
“`html
<h3>History</h3>
<ul id=“transactions-list” class=“transactions”>
<!— Individual transactions will be added here
dynamically —>
</ul>
“`
8. Conclusion
With this structure in place, we’ve laid the groundwork
for our Expense Tracker. The next steps will involve
styling with CSS to make it visually appealing and then
adding interactivity with JavaScript. Remember, a strong
foundation with HTML is crucial, as it ensures our
application is both functional and accessible.
Project CSS
In this chapter, we’ll be diving deep into the styling of our
“Expense Tracker” project. CSS, short for Cascading
Style Sheets, is the language we use to design our web
applications. It controls everything from the layout to the
fonts, colors, and animations, creating a compelling user
interface that’s both functional and aesthetically
pleasing.
4. Header Styles
A bold header will help users quickly identify the app:
“`css
header {
text-align: center;
margin-bottom: 20px;
}
header h2 {
font-size: 2rem;
color: 333;
}
“`
6. Displaying Transactions
Expenses will be listed in rows. Positive values (income)
will be displayed in green, while negative values
(expenses) will be in red for easy differentiation:
“`css
.transaction {
display: flex;
justify-content: space-between;
padding: 10px;
border-bottom: 1px solid ddd;
}
.transaction.income {
color: green;
}
.transaction.expense {
color: red;
}
“`
8. Responsive Design
Given the increasing number of users accessing apps
from mobile devices, we must ensure our design looks
great on smaller screens:
“`css
@media (max-width: 480px) {
.container {
width: 95%;
}
.overview {
flex-direction: column;
}
.total, .income, .expense {
width: 100%;
margin-bottom: 10px;
}
}
“`
Summary
The styling of our “Expense Tracker” app emphasizes
clarity and user-friendliness. We’ve used a combination
of layouts, color schemes, and responsive design to
ensure our application looks and functions well across
various devices. In the next chapters, we’ll dive into the
functionality of our app, where we’ll employ JavaScript to
bring our Expense Tracker to life.
2. CSS Styling
To make our transaction list visually appealing, let’s style
it:
“`css
.transactions {
margin: 20px 0;
border: 1px solid e0e0e0;
padding: 10px;
}
.transactions h2 {
text-align: center;
margin-bottom: 15px;
}
transaction-list {
list-style-type: none;
padding: 0;
}
transaction-list li {
display: flex;
justify-content: space-between;
padding: 8px 0;
border-bottom: 1px solid e0e0e0;
}
“`
3. JavaScript Implementation
First, select the transaction list in your JavaScript:
“`javascript
const transactionList =
document.getElementById(‘transaction-list’);
“`
Assuming you have an array of transaction objects
named `transactions` (which will be filled with user input
or data from local storage), we will use the following
function to display them:
“`javascript
function displayTransactions() {
// Clear out any current transaction items in the list
transactionList.innerHTML = ”;
// Loop through the transactions array and display
each one
transactions.forEach(transaction => {
const item = document.createElement(‘li’);
item.innerHTML = `
<span>${transaction.description}</span>
<span>${transaction.amount > 0 ? ‘+’ :
‘-‘}$${Math.abs(transaction.amount)}</span>
`;
item.classList.add(transaction.amount > 0 ?
‘income’ : ‘expense’);
transactionList.appendChild(item);
});
}
“`
This function first clears any current transactions in the
list. Then, for each transaction in our `transactions`
array, it creates a new list item (`li`) element, sets its
inner HTML to display the transaction’s description and
amount, adds a class based on whether the transaction
is an income or an expense, and then appends the item
to our `transaction-list`.
Conclusion
With the above steps, we’ve successfully implemented
the functionality to display transaction items in our
Expense Tracker project. As users add or remove
transactions, the list will update dynamically, providing a
clear and concise view of their financial activities. In
subsequent chapters, we will build upon this foundation
by adding more features, such as calculating and
displaying balances, incomes, and expenses. Stay
tuned!
3. Calculation Function
Now, let’s create a function that calculates the balance,
income, and expense based on the transaction data.
“`javascript
function calculateTotals(transactions) {
income = transactions
.filter(transaction => transaction.amount > 0)
.reduce((acc, transaction) => acc +
transaction.amount, 0);
expense = transactions
.filter(transaction => transaction.amount < 0)
.reduce((acc, transaction) => acc +
transaction.amount, 0) * -1; // We multiply by -1 to get a
positive number
balance = income - expense;
}
“`
Note: In the function above, we’re using array methods
`filter()` and `reduce()` to calculate our income, expense,
and balance.
Conclusion
Our Expense Tracker now not only adds or removes
transactions but also provides a clear overview of a
user’s financial status by displaying the balance, income,
and expense in real-time. By integrating with local
storage, we ensure that our data remains persistent
across sessions. This project demonstrates the power of
Vanilla JavaScript in building dynamic applications
without relying on any libraries or frameworks. As we
progress, we will continue adding more functionalities to
this project, making it a comprehensive tool for anyone
wishing to track their expenses.
Exercise:
1. Add functionality to handle different currencies.
2. Enhance the UI to differentiate between positive and
negative balances visually.
3. Extend the tracker to categorize expenses and
represent them in a pie chart.
3. Storing Transactions
We will store our transactions in an array and later save
them to local storage.
“`javascript
let transactions = [];
function addTransaction(e) {
e.preventDefault();
if (transactionNameEl.value.trim() === ” ||
transactionAmountEl.value.trim() === ”) {
alert(‘Please enter a valid name and amount for the
transaction.’);
return;
}
const newTransaction = {
id: generateID(),
name: transactionNameEl.value,
amount: parseFloat(transactionAmountEl.value)
};
transactions.push(newTransaction);
updateLocalStorage();
updateUI();
transactionNameEl.value = ”;
transactionAmountEl.value = ”;
}
function generateID() {
return Math.floor(Math.random() * 100000000);
}
“`
4. Displaying Transactions
Once a transaction is added, we need to display it to the
user.
“`javascript
function updateUI() {
const transactionListEl =
document.getElementById(‘transaction-list’);
transactionListEl.innerHTML = ”;
transactions.forEach(transaction => {
const sign = transaction.amount < 0 ? ‘-‘ : ‘+’;
const item = document.createElement(‘li’);
item.className = transaction.amount < 0 ? ‘minus’ :
‘plus’;
item.innerHTML = `
${transaction.name}
<span>${sign}${Math.abs(transaction.amount)}</span>
<button class=“delete-btn”
onclick=“deleteTransaction(${transaction.id})”>x</button
>
`;
transactionListEl.appendChild(item);
});
}
“`
5. Deleting Transactions
For deletion, we can utilize the unique ID we’ve given to
each transaction.
“`javascript
function deleteTransaction(id) {
transactions = transactions.filter(transaction =>
transaction.id !== id);
updateLocalStorage();
updateUI();
}
“`
7. Event Listeners
Finally, we attach an event listener to our add button:
“`javascript
document.getElementById(‘add-
transaction’).addEventListener(‘click’, addTransaction);
“`
And voilà! With these functionalities in place, users can
seamlessly add and delete transactions. The
transactions are not only reflected in the UI but are also
stored in the browser’s local storage, ensuring no data is
lost even if the user refreshes the page.
Remember, while the above code snippets provide a
solid foundation for an expense tracker, there are various
enhancements and additional features you can
incorporate. As always, testing each functionality
thoroughly ensures a smooth user experience.
Important Considerations:
- JSON Parsing and Stringifying: Local Storage only
stores strings. So, when saving arrays or objects, you’ll
need to stringify them first using `JSON.stringify()`.
When retrieving them, parse them back into a usable
format with `JSON.parse()`.
- Limitations: While the 5-10 MB limit is generous for
many applications, be aware of it. If there’s a potential
for your application to store a large amount of data, you
may want to consider other options or strategies like
IndexedDB or even server-side storage.
- Security: Local Storage is not designed for sensitive
data. Since it’s accessible via JavaScript, it’s open to
potential XSS attacks. Always ensure you validate and
sanitize your data.
Conclusion:
Local Storage is a powerful tool in a web developer’s
arsenal, offering a simple and efficient way to enhance
user experience through data persistence. In our
Expense Tracker application, it provides an essential
bridge between sessions, ensuring that our users never
lose track of their transactions. As with all tools, it’s
crucial to be aware of its limitations and use it judiciously.
Section 11:
Project 10 - Infinite Scroll
Posts | Fetch, Async/Await,
CSS Loader
Project Intro
Welcome to the tenth project of our journey, “Infinite
Scroll Posts”. This project promises to be an engaging
endeavor into the world of fetching data from APIs,
utilizing asynchronous JavaScript operations, and
enhancing the user experience with visually pleasing
CSS loader animations. So, without further ado, let’s
dive into what this project entails.
1. Overview
In the modern era of the web, user experience stands
paramount. An aspect of this user experience is the
ability to fetch and display content without any noticeable
interruptions. Gone are the days when users were
accustomed to clicking ‘Next’ on pagination. Now, they
expect content to automatically load as they scroll,
popularly known as infinite scrolling. This feature can be
seen on numerous modern websites, from social media
platforms like Twitter and Facebook to news websites.
2. Objectives
By the end of this project, you will:
- Understand the basics and the mechanics behind the
infinite scroll feature.
- Fetch data from a public API using Fetch and
Async/Await.
- Display this fetched data seamlessly as the user scrolls
down the page.
- Enhance the user experience by adding a CSS loader
animation to indicate data fetching.
4. What to Expect?
Here’s a snapshot of what the final product will look like:
1. Initial Load: When the user first visits the site, a
predefined number of posts will be displayed on the
screen.
2. Scrolling: As the user scrolls down, just before
reaching the bottom, new posts will automatically start
loading, enhancing the UX.
3. Loader Animation: While new posts are fetched, a
loader will be displayed at the bottom, indicating to the
user that content is being loaded.
4. Error Handling: In cases where the data cannot be
fetched, perhaps due to network issues or API limits, the
user will be notified appropriately.
5. Pre-requisites
Before diving into this project, it’s beneficial if you’re
familiar with:
- Basic HTML/CSS for structure and styling.
- Fundamentals of JavaScript, especially promises.
- Basic understanding of how APIs work.
Project HTML
Welcome to Chapter 51, where we’ll be delving into the
HTML structure for our Infinite Scroll Posts project. This
project is particularly exciting as it brings together the
power of Fetch API, asynchronous functions, and some
smooth CSS animations. The HTML structure forms the
foundation on which our CSS and JavaScript will
operate, so let’s make sure we lay a strong foundation!
1. Project Overview
In the Infinite Scroll Posts project, we aim to create a
web application where users can infinitely scroll through
a series of posts, just like how it works on many social
media platforms. As users scroll to the end of the page,
new posts are fetched from an API and displayed
seamlessly. In addition, a CSS loader will signal to the
user that more content is being loaded.
4. Loader
As we’re implementing infinite scrolling, we need a
loader to inform users when new posts are being
fetched:
“`html
<div class=“loader”>
Loading…
</div>
“`
(Note: The actual visual representation of the loader will
be controlled using CSS. In our JavaScript, we will
programmatically show or hide this loader based on
whether we’re fetching data.)
5. Error Message
In case there’s an issue fetching posts, it’s good UX to
have a designated area to display an error message:
“`html
<div class=“error-message”>
<!— Error messages will be inserted here —>
</div>
“`
6. Adding Metadata
It’s good practice to include meta tags to improve SEO
(Search Engine Optimization) and ensure a good display
when shared on platforms like Facebook or Twitter:
“`html
<meta name=“description” content=“Infinite Scroll Posts:
Dive into endless content from our API.”>
<meta property=“og:title” content=“Infinite Scroll Posts”>
<meta property=“og:description” content=“Experience
the magic of infinite scrolling with posts fetched in real-
time from our API.”>
<meta property=“og:image”
content=“path_to_thumbnail_image.jpg”>
“`
Replace `path_to_thumbnail_image.jpg` with the path to
your chosen thumbnail image for sharing on social
platforms.
7. Closing Thoughts
The HTML structure we’ve laid out here forms the base
of our Infinite Scroll Posts project. While it might look
simple, remember that the magic happens when our
CSS and JavaScript come into play, making this
structure come to life.
In the following chapters, we’ll be styling this structure
using CSS and then adding the functionality with
JavaScript. Stick around to see how our simple HTML
transforms into a dynamic infinite scrolling experience!
Conclusion
CSS plays a vital role in enhancing user experience,
especially for web applications like our Infinite Scroll
Posts project. With a visually appealing design and a
smooth loader animation, we’re making the user
experience delightful and intuitive.
In the next chapter, we will focus on fetching the initial
posts and populating our page with content. This will be
where the real magic happens, as we combine our CSS
designs with dynamic JavaScript functionalities. Stay
tuned!
Conclusion
In this chapter, we covered how to use the Fetch API
combined with Async/Await to retrieve initial posts from
an API endpoint. We also looked at how to display these
posts on our webpage. In the next chapter, we will add
the infinite scrolling feature, which will load more posts
as the user scrolls down the page.
Remember, while `jsonplaceholder` is great for learning
and testing, in a real-world application, you’d be working
with your own backend or a third-party service that
provides the content you need. Always ensure you
handle errors gracefully to enhance the user experience.
Prerequisites:
1. A working knowledge of JavaScript, particularly ES6+
features such as Async/Await.
2. Familiarity with the DOM (Document Object Model)
and manipulating it with JavaScript.
3. Previous chapters in this project where we set up
fetching posts and infinite scrolling.
Step 1: Setting up the Filter Input Field
We need an input field where users can type search
queries:
“`html
<input type=“text” id=“filter” placeholder=“Filter posts…”>
“`
Step 3: Enhancements
a. Adding a Delay: Instant filtering can be jarring,
especially with larger datasets. Consider adding a delay
using `setTimeout`.
b. Spinner or Loader: If filtering takes time, showing a
spinner can enhance user experience. You can reuse
the CSS loader implemented in previous chapters.
c. Highlighting Matched Text: Enhance user experience
by highlighting the matched text within the post. This can
be achieved using Regex and manipulating the
innerHTML property of post elements.
Conclusion:
Filtering is a powerful feature that greatly enhances user
experience, allowing users to quickly and efficiently find
the information they’re looking for. With the
implementation above, users of your infinite scroll post
project can now search through posts with ease.
Objectives
By the end of this project, you will be able to:
1. Understand the fundamentals of the Web Speech API
and its role in modern web applications.
2. Implement the Speech Synthesis interface to convert
textual data into speech.
3. Customize voice selections, pitch, and rate of speech.
4. Design a user-friendly interface that facilitates easy
text input and speech output.
Pre-requisites
While this project is tailored for learners who have some
experience with HTML, CSS, and JS, it’s designed to be
approachable for beginners as well. If you’re completely
new to these technologies, it might be beneficial to revisit
the introductory chapters or courses as mentioned in the
book description.
Summary
This chapter introduced the basic HTML structure
required for our Speech Text Reader application. We
designed speech boxes to house preset phrases that
users can click on to hear them spoken aloud. In the
following chapters, we will delve into the Speech
Synthesis API and the corresponding JavaScript to bring
our speech boxes to life.
The visual appearance of our speech boxes and the
overall layout can be improved and made interactive with
CSS, which we will cover in the next chapter.
Project CSS
Welcome to the CSS styling part of our Speech Text
Reader project! Having completed the HTML structure,
we now need to enhance its look and feel to make it both
user-friendly and attractive. In this chapter, we’ll walk
through every CSS property and style we’ll apply to our
Speech Text Reader to make it come to life.
2. Main Container
Our main container will center everything on the screen
and give a gentle shadow for depth.
“`css
.container {
max-width: 800px;
margin: 50px auto;
padding: 20px;
background: fff;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
“`
3. Heading
The heading style will be bold, centered, and have a bit
more space on the bottom margin to separate it from the
content below.
“`css
h1 {
text-align: center;
font-size: 2em;
margin-bottom: 20px;
}
“`
Conclusion
With the styles set up, our Speech Text Reader should
look polished and be user-friendly. These styles enhance
the usability of the application and create a pleasant
experience for the user. In the next chapter, we’ll dive
into JavaScript to integrate the Web Speech API,
allowing the user to transform text into spoken words.
Understanding SpeechSynthesis
Before diving into retrieving available voices, it’s
essential to grasp the basics of `SpeechSynthesis`. It’s
the primary interface for controlling text-to-speech on a
web page. This interface possesses a method called
`getVoices()`, which returns an array of
`SpeechSynthesisVoice` objects representing all the
voices available.
Conclusion
Integrating dynamic voice selection into your Speech
Text Reader enhances customization, catering to a
global audience with varying linguistic preferences. With
just a few lines of code, the Web Speech API’s
SpeechSynthesis interface grants your web applications
a powerful tool, breathing life into static text. As you
progress, consider exploring other features like adjusting
pitch, rate, and volume to further tailor the user’s
auditory experience.
Speech Bu ons
In this chapter, we’ll explore one of the core components
of our Speech Text Reader project: the Speech Buttons.
These buttons will serve as the trigger for our application
to start converting the selected or entered text into
audible speech. Harnessing the power of the Web
Speech API, particularly the Speech Synthesis interface,
we will give our application a voice.
Prerequisites
Before diving into this chapter, ensure you’ve
successfully set up the basic structure of the project as
covered in the previous chapters.
JavaScript Implementation
Now, let’s harness the power of the Web Speech API:
1. Selecting our Elements:
Using JavaScript, we first need to select our button
elements:
“`javascript
const startBtn = document.getElementById(‘start’);
const stopBtn = document.getElementById(‘stop’);
“`
2. Initializing Speech Synthesis:
Next, we initialize our SpeechSynthesis object:
“`javascript
const synth = window.speechSynthesis;
“`
3. Start Speaking Button:
The Start Speaking button will take the provided text and
convert it into speech. Let’s see how this is done:
“`javascript
startBtn.addEventListener(‘click’, () => {
if (synth.speaking) {
console.error(‘Speech synthesis is already
speaking.’);
return;
}
let textInput = document.getElementById(‘text-
input’).value; // Assuming ‘text-input’ is the ID of the
textarea or input where users type/paste their text
if (textInput !== ”) {
let utterance = new
SpeechSynthesisUtterance(textInput);
// Optional: Set voice, pitch, and rate here
// utterance.voice = synth.getVoices()[0];
// utterance.pitch = 1;
// utterance.rate = 1;
synth.speak(utterance);
}
});
“`
4. Stop Speaking Button:
The Stop Speaking button will halt any ongoing speech
synthesis:
“`javascript
stopBtn.addEventListener(‘click’, () => {
if (synth.speaking) {
synth.cancel();
}
});
“`
Conclusion
The Speech Buttons play a pivotal role in our Speech
Text Reader application, allowing users to control when
text-to-speech conversion begins and ends. Leveraging
the capabilities of the Web Speech API, we’ve managed
to introduce a powerful feature with just a few lines of
code. In the upcoming chapters, we’ll explore more
features and functionalities to make our application more
robust and user-friendly.
Conclusion
With the steps outlined above, we’ve successfully added
functionalities to change the voice of our Speech Text
Reader and allow users to input custom text for the
application to read out loud. This not only makes our
application more versatile but also enhances the user
experience by providing more control over the content
and its presentation.
Remember, accessibility tools like these can make a
difference in how users interact with web applications.
Always ensure that you test these tools with a variety of
users to guarantee that they cater to different needs.
Conclusion
We have now successfully created a large circle which
will serve as the core visual element for our Relaxer App.
This circle will soon be animated to assist users in a
relaxing breathing exercise. In the next chapters, we will
dive deeper into adding animations and enhancing the
interactivity of this circle.
Remember, the effectiveness of this app isn’t just about
the animations or the code, but also about the visual
cues that can help users find relaxation and calmness.
Our choice of colors, positioning, and the smoothness of
animations will play a crucial role in the app’s overall
impact.
Crea ng & Anima ng The
Pointer
In this chapter, we will be focusing on an integral part of
the Relaxer App: the pointer. The pointer serves as a
visual cue to guide the user through their breathing
exercises. It will rotate around the circumference of a
circle, with its motion corresponding to the breathing
instructions.
Prerequisites
Before we begin, ensure you have the following set up:
- Basic HTML structure for the Relaxer App
- A large circle in the center of the page (from Chapter
70)
Conclusion
The animated pointer now provides a clear visual cue for
users, guiding them through the breathing exercise. By
combining CSS animations with timed JavaScript
functions, we’ve created a seamless user experience
that’s both interactive and beneficial for relaxation.
In the next chapter, we’ll delve into triggering the
breathing animation with JavaScript, enhancing the
relaxation experience further. Stay tuned!
6. Conclusion
With this, our breath animation is complete. The `Relaxer
App` now provides a visual aid for users to synchronize
their breathing. CSS animations combined with
JavaScript triggers offer a dynamic way to provide
engaging content for users.
By following this model, you can expand upon this
concept to include sound, adjust timings, or even include
varying breathing patterns for different relaxation
techniques.
Key Features
1. Dynamic Date & Time Integration: Using the
JavaScript Date object, the application will continually
fetch the current date and time, calculate the difference
from the New Year, and display the countdown.
2. Landing Page: A beautifully designed landing page
that captivates users with animations, relevant images,
and, of course, the countdown itself.
3. Responsive Design: We want everyone, regardless of
their device, to enjoy the countdown. Hence, we’ll make
sure our design is responsive, looking great on both
mobiles and desktops.
4. Spinner Effect: Just before the countdown hits the
New Year, we’ll have a spinner effect to add to the
anticipation.
5. Dynamic Year Update: No need to manually update
the target year. Our app will automatically set the
countdown for the next New Year.
3. Conclusion
With our landing page’s HTML and styling complete, we
now have a base from which we can implement our
countdown timer in the upcoming chapters. The dark
theme accented with gold adds a touch of festivity and
anticipation for the New Year’s countdown.
In the next chapter, we’ll focus on creating the actual
countdown, adding days, hours, minutes, and seconds
dynamically, and using JavaScript to make it all function
in real-time.
Closing Thoughts
Countdowns can be a thrilling addition to many websites,
especially those anticipating an event. By mastering the
Date object and understanding the mathematics behind
time calculations, you can create a plethora of time-
based functionalities for the web. As always, practice
makes perfect. Try creating countdowns for other events
or adding features like custom user inputs for
personalized countdowns. The sky’s the limit!
Wrapping Up
With our dynamic year in place and a pleasant loading
spinner to greet our users, our New Year Countdown is
taking shape!
Remember, the power of web development is not just in
creating beautiful visuals but in enhancing user
experience with these small dynamic functionalities. The
countdown becomes more robust and user-friendly,
ensuring our users return year after year.
Technical Overview
In this project, we’ll harness the capabilities of the
HTML5 Drag & Drop API. Here are the primary
components we will be focusing on:
1. Draggable Elements: These are the items in our list
that we want to make movable.
2. Drop Zones: These are the areas where we can place
our draggable elements.
3. Drag & Drop Events: These are a set of events that
the browser triggers as elements are dragged and
dropped. We’ll be leveraging events like `dragstart`,
`dragover`, `dragleave`, and `drop`.
Expected Outcomes
By the end of this project:
- You’ll have a functional sortable list that allows items to
be rearranged using drag and drop.
- You’ll gain a deep understanding of the Drag & Drop
API, its events, and methods.
- You’ll be able to implement drag & drop functionality in
different scenarios, not just for sorting lists.
Prerequisites
While we will be explaining each step in detail, it’s
essential to have a basic understanding of:
- HTML: To structure our list.
- CSS: For styling our list and creating visual cues during
the drag & drop process.
- JavaScript: To handle drag & drop events and
manipulate the DOM.
In Conclusion
The Drag & Drop API opens up a world of interactive
possibilities on the web. Whether it’s building a game, a
planner, or a visual organizer, understanding how to
harness its power can set your projects apart.
Are you excited? Let’s dive right into building our
sortable list!
Conclusion
Being able to manipulate the DOM is a fundamental skill
for a web developer. By now, you should have a good
understanding of how to insert list items into the DOM
dynamically using JavaScript. In the next chapter, we’ll
learn how to scramble these list items and set the stage
for our drag-and-drop functionality. Stay tuned!
Conclusion
By introducing a scrambling feature, you’ve added an
interactive layer to your sortable list application. This
challenges the users, but also gives them a tangible
goal: to restore order. In the next chapter, we’ll delve into
the core styling of our application and set the visual
stage for our drag and drop functionality. Remember,
user experience is paramount, and the visual feedback
we provide is crucial in guiding users through the sorting
process.
Core CSS
CSS, or Cascading Style Sheets, is an essential tool for
controlling the look and feel of your web applications. In
this chapter, we’ll be diving into the core CSS that will
give our Sortable List project a clean, professional
appearance. Remember, good CSS not only makes your
application visually appealing, but it can also enhance
user experience.
6. Additional Touches:
Finally, you can add some additional touches to improve
the aesthetics and user experience. Consider adding
`hover` effects, transitions, and possibly some
responsive media queries to ensure your sortable list
looks good on all devices.
Conclusion:
CSS is a powerful tool that enables web developers to
create visually appealing and intuitive user interfaces. By
using thoughtful and purposeful styles, you can
significantly improve user experience. In the next
chapters, we’ll integrate the drag and drop API
functionality into our styled sortable list, adding
functionality to our visually appealing design.
Remember, always test your designs on various devices
and browsers to ensure consistency and optimal user
experience.
Conclusion
The Drag and Drop API provides a powerful way to
implement intuitive interactions in your web projects.
With this API, we can create visually appealing
interfaces where users can directly manipulate on-
screen elements, making for a more dynamic and
engaging user experience.
Check Order
After mastering the art of dragging and dropping items
on our sortable list, the next vital step is to check the
order of the items. This ensures that users receive
feedback on their effort, thereby making the sortable list
interactive and intuitive.
In this chapter, we’ll focus on determining the correct
order of the items after they’ve been sorted. We’ll walk
through creating a function to validate the order, and
then provide feedback to the user based on their sorting
performance.
Prerequisites
Before delving into the code, ensure that:
- You have a working drag and drop functionality from
the previous chapters.
- You have a predetermined correct order for the list
items to compare against.
Providing Feedback
Once we’ve determined whether the order is correct or
not, it’s essential to provide feedback to the user.
“`javascript
function provideFeedback() {
const isOrderCorrect = checkOrder();
if (isOrderCorrect) {
alert(“Congratulations! You’ve sorted the list
correctly.”);
} else {
alert(“Oops! That doesn’t seem right. Try again.”);
}
}
“`
Now, we’ll call `provideFeedback` every time a list item is
dropped.
Hooking Up the Feedback Function to Drag & Drop
Update your `drop` event listener:
“`javascript
listItem.addEventListener(‘drop’, function(e) {
// … existing drag & drop logic …
provideFeedback();
});
“`
Now, every time an item is dropped, the order is
checked, and feedback is provided.
Enhancements
1. Highlight Incorrect Items: Instead of a simple alert, you
can add a red border or change the background color of
incorrect items to visually guide users.
2. Add a “Check Order” Button: Instead of checking
immediately upon every drop, you could add a button
that allows users to check their order when they feel
they’ve sorted it correctly.
Conclusion
Incorporating feedback mechanisms, such as checking
the order in our sortable list, greatly enhances the user
experience. It transforms the list from a simple sorting
activity into a more interactive and engaging puzzle.
Always remember, providing real-time feedback is crucial
in any interactive web application, ensuring users remain
engaged and informed about their actions.
As you progress with web development, consider diving
deeper into the Drag & Drop API to explore other
possibilities, like multi-list dragging, clone dragging, and
more!
Section 16: Project 15 -
Breakout Game | HTML5
Canvas API
Project Intro
Welcome to Project 15, the “Breakout Game” using the
HTML5 Canvas API! If you’ve ever had a taste of classic
arcade games, you’re in for a delightful trip down
memory lane. If not, prepare to experience one of the
gems of yesteryears that laid the foundation for many
modern games.
Prerequisites
Before we start, make sure you’re familiar with basic
JavaScript concepts, as we’ll be writing game logic in JS.
Knowledge of arrays, loops, and conditional statements
will be beneficial. Don’t worry if you’re new to the Canvas
API; we’ll cover everything step-by-step.
Summary:
With our page structure in place and styles applied,
we’ve created a solid foundation for our Breakout game.
This ensures our game mechanics, which we’ll dive into
in the next chapters, will be showcased on a polished
and professional-looking stage.
Remember, the design is a critical part of game
development. It’s not just about how it looks but also how
it feels. So, always take the time to refine and perfect the
environment in which your game operates. In the
following chapters, we’ll bring our Breakout game to life
using the HTML5 Canvas API. Stay tuned!
1. Introduction to Canvas
Before we jump into the specifics of our Breakout game,
let’s briefly recap what the Canvas is. The HTML5
`<canvas>` element is used to draw graphics, on the fly,
via scripting (usually JavaScript). It allows for dynamic,
scriptable rendering of 2D shapes and bitmap images.
4. Coordinate System
The canvas has a built-in coordinate system. The top-left
corner of the canvas is defined as point (0,0). All
elements are placed relative to this point. As we go
downwards, the y-coordinate increases; as we go to the
right, the x-coordinate increases.
5. Ball Dynamics
- Initial Position: Center of the canvas.
- Movement: The ball will move both in the x and y
directions.
- Collision: We will need to detect collisions with the
paddle, the bricks, and the canvas edges.
6. Paddle Dynamics
- Initial Position: Centered horizontally at the bottom of
the canvas.
- Movement: The paddle will only move horizontally,
controlled by the user.
- Width and Height: These dimensions will be constants
that we can tweak as per our game’s requirement.
7. Brick Configuration
- Rows and Columns: We’ll design a pattern of bricks
using multiple rows and columns.
- Brick Size: Each brick will have a uniform size, but we
can adjust this to fit our design.
- Gaps: There will be small gaps between bricks to
distinguish them clearly.
9. Color Scheme
A consistent and visually pleasing color scheme is
essential. For our game, we’ll be choosing:
- Ball: Red
- Paddle: Black
- Bricks: A gradient of blues (this will add a dynamic feel)
- Background: Light grey
- Score & Life Display: Dark grey with white text
Conclusion
The canvas offers a plethora of opportunities for web-
based game development. By understanding its
capabilities and planning our game’s structure, we set
the stage for smooth development in subsequent
chapters. In the upcoming chapters, we’ll delve into the
specifics of each game element, starting with drawing
the ball and paddle on our canvas. Stay tuned!
8. Let’s Play!
To kick things off, simply call the `draw()` function:
“`javascript
draw();
“`
This will initiate our game loop and you’ll see the ball,
paddle, and score on the canvas.
Summary
In this chapter, we’ve successfully drawn our ball and
paddle using the HTML5 Canvas API and started
keeping score. As we progress further, we’ll add the
ability to move the paddle, bounce the ball, and break
the bricks. This is just the beginning of our Breakout
game journey!
Brick Configuration
Before diving into the code, let’s outline the properties
our bricks will have:
- Width & Height: The dimensions of each brick.
- Padding: Space between each brick.
- Offset: Initial top and left space to start drawing the
bricks.
- Color: The color of the bricks.
- Row & Column: Number of rows and columns for our
bricks.
Conclusion
Our Breakout game now has bricks that serve as
obstacles for the player. In the following chapters, we’ll
look into how our ball will interact with these bricks,
removing them when hit, and how to increase the
game’s difficulty as the player progresses.
Remember, the beauty of game development lies in
creativity. You can adjust the properties, colors, and
behaviors of bricks to create unique challenges and
designs. Happy coding!
Move Paddle
Welcome to Chapter 88, where we will delve into the
mechanics of moving the paddle in our Breakout Game.
The paddle movement is essential for gameplay,
allowing players to deflect the ball and target bricks.
1. Introduction
In the world of gaming, the paddle is the player’s only
defense against the bouncing ball, preventing it from
falling off the screen and enabling the player to aim
where they want the ball to go. Using the HTML5
Canvas API, we will be creating this paddle and enabling
its movement.
6. Conclusion
With these steps, the paddle should move smoothly
across the canvas, providing the player with a tool to
bounce the ball and break the bricks. Remember,
adjusting `paddleDX` can change the difficulty level of
your game, making it easier or harder for the player.
In the next chapter, we’ll dive into moving the ball, which,
combined with this paddle movement, will form the core
gameplay of our Breakout Game.
Ball Movement
The first thing we need to achieve is to get our ball
moving. For this, we’ll update the ball’s `x` and `y`
position on every frame.
“`javascript
let ball = {
x: canvas.width / 2,
y: canvas.height - 30,
dx: 2,
dy: -2,
radius: 10
};
“`
In the code above, `dx` and `dy` represent the change in
`x` and `y` position respectively. If `dx` is positive, the
ball moves to the right. If `dy` is negative, the ball moves
upwards.
Conclusion
By now, you should have a moving ball that can break
bricks upon collision. By combining ball movement with
brick collision, our Breakout game begins to take shape.
In the next chapter, we will focus on handling when the
ball hits the game boundaries, the paddle, and resetting
the game when the player loses.
5. Enhancements
There are several enhancements you can add to make
the game-over experience more polished:
- Fade Effects: Use global alpha and gradually decrease
it to create a fade-out effect when the game is over.
- Custom Messages: Display custom messages for
different score ranges, encouraging the player to try
again or congratulating them on a high score.
- Persistent High Scores: Using the `localStorage` API,
you can store the player’s high score on their browser,
so they can see their best scores across sessions.
6. Conclusion
Handling the game over condition and providing a
smooth reset experience is crucial for player retention
and satisfaction. By clearly defining the end condition,
giving immediate feedback, and making it easy to dive
back in and play again, you ensure that players remain
engaged and motivated to improve.
In the next chapter, we’ll explore further enhancements
and features that can elevate the gameplay experience.
Remember, while the technical execution is essential, it’s
the small details in game development that often make
the most significant difference in the player’s experience.
Conclusion
Congratulations on reaching the end of “15 Web Projects
With Vanilla JavaScript.” You’ve just walked through a
series of fascinating, hands-on projects that pushed your
understanding of web development using pure HTML5,
CSS, and JavaScript. No frameworks, no libraries—just
the raw power of core web technologies.
Reflecting on our journey, we started with the basics,
learning the foundations of web development, and then
dove deep into understanding how JavaScript interacts
with the browser to create dynamic, interactive
experiences. From simple form validation, managing
local storage, exploring asynchronous programming,
manipulating the DOM, to understanding the intricacies
of various APIs—every project was an opportunity to
harness new skills.