5 JavaScript Coding Projects
JavaScript code Example Random Quote Generator Project: Random Quote
Generator 3
Step 1: HTML Structure 3
Step 2: CSS Styling 4
Step 3: JavaScript Logic 6
Step 4: Testing 7
Step by Step Explanation: 9
JavaScript code Example ToDo List JavaScript project that creates a basic to-do
list application 10
Project: Simple To-Do List App 11
Step 1: HTML Structure 11
Step 2: CSS Styling 12
Step 3: JavaScript Logic 14
Step 4: Testing 15
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
1
JavaScript Code Details 15
Step by Step Explanation: 17
JavaScript code Example Create a Digital Clock Project: Digital Clock 19
Step 1: HTML Structure 19
Step 2: CSS Styling 20
Step 3: JavaScript Logic 22
Step 4: Testing 23
JavaScript Code Color Flipper Example Project: Color Flipper 27
Step 1: HTML Structure 27
Step 2: CSS Styling 28
Step 3: JavaScript Logic 30
Step 4: Testing 30
Step 1: Get References to HTML Elements 31
Step 2: Attach Event Listener 32
Step 3: Define the flipColor Function 32
Step 4: Testing 33
JavaScript Code Tip Calculator Example Project: Tip Calculator 34
Step 1: HTML Structure 34
Step 2: CSS Styling 36
Step 3: JavaScript Logic 38
Step 4: Testing 40
Here's the detailed breakdown of the JavaScript code: 40
Step 1: Get References to HTML Elements 41
Step 2: Attach Event Listener 42
Step 3: Define the calculateTip Function 42
Here's a detailed breakdown of the calculateTip function: 43
Step 4: Testing 44
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
2
JavaScript code Example Random Quote Generator
Project: Random Quote Generator
Step 1: HTML Structure
Create an HTML file named [Link] and set up the basic structure.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
3
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Random Quote Generator</title>
<link rel="stylesheet" href="[Link]">
</head>
<body>
<div class="container">
<h1>Random Quote Generator</h1>
<p id="quote">Click the button to generate a random quote.</p>
<button id="generateButton">Generate Quote</button>
</div>
<script src="[Link]"></script>
</body>
</html>
Step 2: CSS Styling
Create a CSS file named [Link] for basic styling.
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
margin: 0;
padding: 0;
display: flex;
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
4
justify-content: center;
align-items: center;
height: 100vh;
}
.container {
background-color: #fff;
padding: 20px;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
width: 300px;
text-align: center;
}
h1 {
font-size: 24px;
}
button {
display: block;
margin: 10px auto;
padding: 8px 16px;
background-color: #007bff;
color: #fff;
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
5
border: none;
border-radius: 3px;
cursor: pointer;
}
Step 3: JavaScript Logic
Create a JavaScript file named [Link] for the application logic.
const quotes = [
"The only way to do great work is to love what you do. - Steve Jobs",
"Innovation distinguishes between a leader and a follower. - Steve Jobs",
"Don't be afraid to give up the good to go for the great. - John D. Rockefeller",
"Success is not final, failure is not fatal: It is the courage to continue that counts.
- Winston Churchill",
"The future belongs to those who believe in the beauty of their dreams. -
Eleanor Roosevelt"
];
const generateButton = [Link]("generateButton");
const quoteElement = [Link]("quote");
[Link]("click", generateRandomQuote);
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
6
function generateRandomQuote() {
const randomIndex = [Link]([Link]() * [Link]);
[Link] = quotes[randomIndex];
}
Step 4: Testing
Open the [Link] file in a web browser. You should see the "Random Quote
Generator" with a button. Clicking the button will replace the quote with a
random quote from the quotes array.
// An array of quotes to display
const quotes = [
"The only way to do great work is to love what you
do. - Steve Jobs",
"Innovation distinguishes between a leader and a
follower. - Steve Jobs",
"Don't be afraid to give up the good to go for the
great. - John D. Rockefeller",
"Success is not final, failure is not fatal: It is
the courage to continue that counts. - Winston
Churchill",
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
7
"The future belongs to those who believe in the
beauty of their dreams. - Eleanor Roosevelt"
];
// Get references to the HTML elements
const generateButton =
[Link]("generateButton");
const quoteElement = [Link]("quote");
// Attach an event listener to the "Generate Quote"
button
[Link]("click",
generateRandomQuote);
// Define the function to generate a random quote
function generateRandomQuote() {
// Generate a random index within the range of the
quotes array
const randomIndex = [Link]([Link]() *
[Link]);
// Display the randomly selected quote in the
quoteElement
[Link] = quotes[randomIndex];
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
8
}
Step by Step Explanation:
1. We start by defining an array called quotes. This array contains a list of
quotes as strings. Each quote includes both the quote itself and its
attributed author.
2. We get references to the HTML elements we'll interact with:
generateButton and quoteElement. The generateButton represents the
"Generate Quote" button, and quoteElement represents the paragraph
where the quote will be displayed.
3. We attach an event listener to the "Generate Quote" button
(generateButton). This listener is set to call the generateRandomQuote
function when the button is clicked.
4. The generateRandomQuote function is defined. This function generates a
random quote and displays it on the webpage.
5. Inside the generateRandomQuote function:
a. We use [Link]() to generate a random decimal between 0
(inclusive) and 1 (exclusive).
b. We multiply the random decimal by the length of the quotes array
using [Link] to get a random number within the range of the
array indices.
c. We use [Link]() to round down the random number to a whole
number, which will be a valid index for the quotes array.
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
9
6. We set the textContent of the quoteElement to the randomly selected
quote from the quotes array using the randomIndex.
By following these steps, the code creates a simple "Random Quote Generator"
that displays a new random quote each time the "Generate Quote" button is
clicked. This is a great example of how JavaScript can be used to create dynamic
and interactive content on a webpage.
JavaScript code Example ToDo List JavaScript project that
creates a basic to-do list application
Here's a simple JavaScript project that creates a basic to-do list application. I'll
provide you with the step-by-step description and the full code for each step.
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
10
Project: Simple To-Do List App
Step 1: HTML Structure
Create an HTML file named [Link] and set up the basic structure.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Simple To-Do List</title>
<link rel="stylesheet" href="[Link]">
</head>
<body>
<div class="container">
<h1>To-Do List</h1>
<input type="text" id="taskInput"
placeholder="Add a new task">
<button id="addButton">Add</button>
<ul id="taskList"></ul>
</div>
<script src="[Link]"></script>
</body>
</html>
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
11
Step 2: CSS Styling
Create a CSS file named [Link] for basic styling.
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
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 2px 4px rgba(0, 0, 0, 0.1);
width: 300px;
}
h1 {
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
12
font-size: 24px;
text-align: center;
}
input[type="text"] {
width: 100%;
padding: 10px;
margin-top: 10px;
border: 1px solid #ccc;
border-radius: 3px;
}
button {
display: block;
margin: 10px auto;
padding: 8px 16px;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 3px;
cursor: pointer;
}
ul {
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
13
list-style: none;
padding: 0;
}
Step 3: JavaScript Logic
Create a JavaScript file named [Link] for the application logic.
const taskInput = [Link]("taskInput");
const addButton = [Link]("addButton");
const taskList = [Link]("taskList");
[Link]("click", addTask);
function addTask() {
const taskText = [Link]();
if (taskText !== "") {
const li = [Link]("li");
[Link] = taskText;
const deleteButton =
[Link]("button");
[Link] = "Delete";
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
14
[Link]("click", () => {
[Link](li);
});
[Link](deleteButton);
[Link](li);
[Link] = "";
}
}
Step 4: Testing
Open the [Link] file in a web browser. You should see the simple to-do list
application with an input field and an "Add" button. Enter tasks and click the
"Add" button to add them to the list. Each task will have a "Delete" button to
remove it from the list.
JavaScript Code Details
// Get references to the HTML elements
const taskInput = [Link]("taskInput");
const addButton = [Link]("addButton");
const taskList = [Link]("taskList");
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
15
// Attach an event listener to the "Add" button
[Link]("click", addTask);
// Define the function to add a task
function addTask() {
// Get the trimmed value from the task input field
const taskText = [Link]();
// Check if the task is not an empty string
if (taskText !== "") {
// Create a new <li> element to represent the
task
const li = [Link]("li");
[Link] = taskText;
// Create a "Delete" button for each task
const deleteButton =
[Link]("button");
[Link] = "Delete";
// Attach an event listener to the "Delete"
button
[Link]("click", () => {
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
16
// Remove the task's corresponding <li>
element
[Link](li);
});
// Append the "Delete" button to the task's
<li> element
[Link](deleteButton);
// Append the task's <li> element to the task
list
[Link](li);
// Clear the input field after adding the task
[Link] = "";
}
}
Step by Step Explanation:
1. We start by getting references to the HTML elements we'll be interacting
with: taskInput, addButton, and taskList. These are obtained using the
getElementById method, which fetches an element by its ID attribute.
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
17
2. We attach an event listener to the "Add" button (addButton). This listener is
set to call the addTask function whenever the button is clicked.
3. The addTask function is defined. This function is responsible for adding a
new task to the list.
4. Inside the addTask function, we retrieve the trimmed value from the task
input field using [Link](). Trimming removes any leading or
trailing spaces, ensuring we don't add empty tasks.
5. We check if the trimmed task text is not an empty string. If it's not empty,
we proceed to create the HTML structure for the new task.
6. We create a new <li> element using [Link]("li") to
represent the task. We set its textContent to the value of the task input.
7. We create a "Delete" button for each task using
[Link]("button"). We set its textContent to "Delete".
8. We attach an event listener to the "Delete" button using
[Link]("click", ...). Inside the listener, we use the
[Link](li) method to remove the task's corresponding <li>
element when the "Delete" button is clicked.
9. We append the "Delete" button to the task's <li> element using
[Link](deleteButton).
10. We append the task's <li> element, including the "Delete" button, to the
task list ([Link](li)).
11. After adding the task to the list, we clear the task input field by setting its
value property to an empty string ([Link] = "").
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
18
By following these steps, the code creates a simple to-do list application where
you can add tasks and delete them using the "Delete" button. This is a basic
example, and you can build upon it by adding more features and functionality to
create a more robust to-do list application.
JavaScript code Example Create a Digital Clock Project:
Digital Clock
Step 1: HTML Structure
Create an HTML file named [Link] and set up the basic structure.
<!DOCTYPE html>
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
19
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Digital Clock</title>
<link rel="stylesheet" href="[Link]">
</head>
<body>
<div class="container">
<h1>Digital Clock</h1>
<p id="time"></p>
</div>
<script src="[Link]"></script>
</body>
</html>
Step 2: CSS Styling
Create a CSS file named [Link] for basic styling.
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
20
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 2px 4px rgba(0, 0, 0, 0.1);
width: 300px;
text-align: center;
}
h1 {
font-size: 24px;
}
#time {
font-size: 36px;
}
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
21
Step 3: JavaScript Logic
Create a JavaScript file named [Link] for the application logic.
const timeElement = [Link]("time");
function updateTime() {
const now = new Date();
const hours = [Link]().toString().padStart(2,
"0");
const minutes =
[Link]().toString().padStart(2, "0");
const seconds =
[Link]().toString().padStart(2, "0");
const timeString =
`${hours}:${minutes}:${seconds}`;
[Link] = timeString;
}
// Call updateTime every second (1000 milliseconds)
setInterval(updateTime, 1000);
// Initial call to display the time immediately
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
22
updateTime();
Step 4: Testing
Open the [Link] file in a web browser. You should see a digital clock displaying
the current time, updating every second.
Congratulations! You've successfully created a simple Digital Clock using HTML,
CSS, and JavaScript. This project demonstrates how to manipulate time and
update content dynamically on a webpage.
Here's the detailed breakdown of the JavaScript code:
We start by selecting the HTML element where we'll display the time using
const timeElement = [Link]("time");.
We define the updateTime function which:
● Gets the current date and time using new Date().
● Extracts the hours, minutes, and seconds components and formats
them with leading zeros using .padStart() method.
● Constructs a time string in the format "HH:MM:SS".
● Updates the content of timeElement with the constructed time
string.
We use setInterval(updateTime, 1000); to call the updateTime function
every 1000 milliseconds (1 second). This ensures that the clock updates
every second.
We also call updateTime(); initially to immediately display the current time
when the page loads.
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
23
Feel free to explore and expand this project further by adding features like
displaying the current date, customizing the clock's appearance, or even
implementing time zones.
// Get reference to the HTML element where the time
will be displayed
const timeElement = [Link]("time");
// Define the function to update the time
function updateTime() {
// Create a new Date object to get the current time
const now = new Date();
// Extract hours, minutes, and seconds from the
Date object
const hours = [Link]().toString().padStart(2,
"0");
const minutes =
[Link]().toString().padStart(2, "0");
const seconds =
[Link]().toString().padStart(2, "0");
// Create a formatted time string in "HH:MM:SS"
format
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
24
const timeString =
`${hours}:${minutes}:${seconds}`;
// Update the text content of the timeElement with
the new time string
[Link] = timeString;
}
// Call updateTime every second (1000 milliseconds) to
keep the clock updated
setInterval(updateTime, 1000);
// Initial call to updateTime to display the time
immediately when the page loads
updateTime();
Step by Step Explanation:
1. We start by getting a reference to the HTML element where we want to
display the time. In this case, it's the timeElement obtained using
[Link]("time").
2. We define the updateTime function which is responsible for updating the
displayed time.
3. Inside the updateTime function:
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
25
a. We create a new Date object called now to capture the current date
and time.
4. We extract the hours, minutes, and seconds components from the now
object using the getHours(), getMinutes(), and getSeconds() methods. We
use the .toString().padStart(2, "0") chain to ensure that single-digit values
are formatted with a leading zero.
5. We construct a formatted time string using template literals (backticks) with
the hours, minutes, and seconds components.
6. We update the text content of the timeElement with the newly formatted
time string using [Link] = timeString.
7. We use the setInterval(updateTime, 1000) function to call the updateTime
function every 1000 milliseconds (1 second). This ensures that the displayed
time updates dynamically every second.
8. Finally, we call updateTime() initially to immediately display the current
time when the page loads.
By following these steps, the code creates a simple digital clock that continuously
updates with the current time. This project demonstrates how to use JavaScript to
interact with date and time objects, format them, and dynamically update content
on a webpage.
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
26
JavaScript Code Color Flipper Example Project: Color
Flipper
Step 1: HTML Structure
Create an HTML file named [Link] and set up the basic structure.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Color Flipper</title>
<link rel="stylesheet" href="[Link]">
</head>
<body>
<div class="container">
<h1>Color Flipper</h1>
<div class="color-box" id="colorBox"></div>
<button id="flipButton">Flip Color</button>
</div>
<script src="[Link]"></script>
</body>
</html>
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
27
Step 2: CSS Styling
Create a CSS file named [Link] for basic styling.
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
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 2px 4px rgba(0, 0, 0, 0.1);
width: 300px;
text-align: center;
}
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
28
h1 {
font-size: 24px;
margin-bottom: 10px;
}
.color-box {
width: 150px;
height: 150px;
margin: 20px auto;
border-radius: 5px;
}
button {
display: block;
margin: 10px auto;
padding: 8px 16px;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 3px;
cursor: pointer;
}
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
29
Step 3: JavaScript Logic
Create a JavaScript file named [Link] for the application logic.
const flipButton =
[Link]("flipButton");
const colorBox = [Link]("colorBox");
const colors = ["#007bff", "#28a745", "#dc3545",
"#ffc107", "#17a2b8", "#343a40"];
[Link]("click", flipColor);
function flipColor() {
const randomIndex = [Link]([Link]() *
[Link]);
[Link] =
colors[randomIndex];
}
Step 4: Testing
Open the [Link] file in a web browser. You should see a Color Flipper with a
colored box and a "Flip Color" button.
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
30
Congratulations! You've successfully created a simple Color Flipper using HTML,
CSS, and JavaScript. This project demonstrates how you can use JavaScript to
change the appearance of an element dynamically based on user interaction.
Here's the detailed breakdown of the JavaScript code:
We start by getting references to the HTML elements we'll be interacting
with: flipButton and colorBox.
We attach an event listener to the "Flip Color" button (flipButton). This
listener is set to call the flipColor function when the button is clicked.
The flipColor function is defined. This function:
● Generates a random index using [Link]() and [Link]()
within the range of the colors array length.
● Sets the background color of the colorBox element to the randomly
selected color from the colors array.
By following these steps, the code creates a simple Color Flipper that changes the
background color of a box each time the button is clicked. This project
demonstrates how JavaScript can be used to modify the visual properties of
elements dynamically.
Step 1: Get References to HTML Elements
const flipButton =
[Link]("flipButton");
const colorBox = [Link]("colorBox");
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
31
In this step, we're using the [Link]() method to retrieve
references to the HTML elements we'll be interacting with:
● flipButton: The "Flip Color" button.
● colorBox: The colored box element where we'll change the background
color.
Step 2: Attach Event Listener
[Link]("click", flipColor);
Here, we're attaching an event listener to the "Flip Color" button. The flipColor
function will be called when the button is clicked.
Step 3: Define the flipColor Function
function flipColor() {
const randomIndex = [Link]([Link]() *
[Link]);
[Link] =
colors[randomIndex];
}
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
32
Here's a detailed breakdown of the flipColor function:
● When the "Flip Color" button is clicked, the flipColor function is executed.
● We use [Link]() to generate a random decimal number between 0
(inclusive) and 1 (exclusive). We then multiply this number by the length of
the colors array to get a random index within the array.
● The [Link]() function is used to round down the decimal index to the
nearest integer, ensuring it's a valid index within the array.
● We access the colors array using the random index to get a randomly
selected color.
● We set the backgroundColor property of the colorBox element to the
randomly selected color. This changes the background color of the box
dynamically.
Step 4: Testing
When the user clicks the "Flip Color" button, the flipColor function is executed.
This function generates a random index, selects a color from the colors array, and
changes the background color of the colorBox element to the selected color.
This project showcases how JavaScript can be used to modify the appearance of
elements on a webpage based on user interactions. It's a simple yet effective
demonstration of how JavaScript can create dynamic and visually engaging web
experiences.
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
33
JavaScript Code Tip Calculator Example Project: Tip
Calculator
Step 1: HTML Structure
Create an HTML file named [Link] and set up the basic structure.
<!DOCTYPE html>
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
34
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Tip Calculator</title>
<link rel="stylesheet" href="[Link]">
</head>
<body>
<div class="container">
<h1>Tip Calculator</h1>
<label for="billAmount">Bill Amount:</label>
<input type="number" id="billAmount"
step="0.01">
<label for="serviceQuality">Service
Quality:</label>
<select id="serviceQuality">
<option value="0.2">Excellent
(20%)</option>
<option value="0.15">Good (15%)</option>
<option value="0.1">Fair (10%)</option>
<option value="0.05">Poor (5%)</option>
</select>
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
35
<button id="calculateButton">Calculate
Tip</button>
<p id="totalTip"></p>
</div>
<script src="[Link]"></script>
</body>
</html>
Step 2: CSS Styling
Create a CSS file named [Link] for basic styling.
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.container {
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
36
background-color: #fff;
padding: 20px;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
width: 300px;
text-align: center;
}
h1 {
font-size: 24px;
margin-bottom: 10px;
}
label {
display: block;
margin-top: 10px;
font-weight: bold;
}
input, select {
width: 100%;
padding: 8px;
margin-top: 5px;
border: 1px solid #ccc;
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
37
border-radius: 3px;
}
button {
display: block;
margin: 10px auto;
padding: 8px 16px;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 3px;
cursor: pointer;
}
#totalTip {
font-size: 18px;
font-weight: bold;
margin-top: 10px;
}
Step 3: JavaScript Logic
Create a JavaScript file named [Link] for the application logic.
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
38
const calculateButton =
[Link]("calculateButton");
const billAmountInput =
[Link]("billAmount");
const serviceQualityInput =
[Link]("serviceQuality");
const totalTipElement =
[Link]("totalTip");
[Link]("click",
calculateTip);
function calculateTip() {
const billAmount =
parseFloat([Link]);
const serviceQuality =
parseFloat([Link]);
if (!isNaN(billAmount) && !isNaN(serviceQuality)) {
const tipAmount = billAmount * serviceQuality;
const totalAmount = billAmount + tipAmount;
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
39
[Link] = `Tip:
$${[Link](2)} | Total:
$${[Link](2)}`;
} else {
[Link] = "Please enter
valid values.";
}
}
Step 4: Testing
Open the [Link] file in a web browser. You should see a Tip Calculator with
input fields for the bill amount and service quality, as well as a button to calculate
the tip.
Congratulations! You've successfully created a simple Tip Calculator using HTML,
CSS, and JavaScript. This project showcases how you can interact with user input
and perform calculations on a webpage.
Here's the detailed breakdown of the JavaScript code:
We start by getting references to the HTML elements we'll be interacting
with: calculateButton, billAmountInput, serviceQualityInput, and
totalTipElement.
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
40
We attach an event listener to the "Calculate Tip" button (calculateButton).
This listener is set to call the calculateTip function when the button is
clicked.
The calculateTip function is defined. This function:
● Retrieves the values entered by the user for the bill amount and
service quality.
● Checks if the entered values are valid numbers using isNaN().
● If the values are valid, it calculates the tip amount and the total
amount (bill amount + tip amount).
● Formats and displays the tip amount and total amount in the
totalTipElement.
By following these steps, the code creates a simple Tip Calculator that calculates
the tip and total amount based on the user's input. This project demonstrates
how JavaScript can be used to perform calculations and dynamically update
content on a webpage.
Step 1: Get References to HTML Elements
const calculateButton = [Link]("calculateButton");
const billAmountInput = [Link]("billAmount");
const serviceQualityInput = [Link]("serviceQuality");
const totalTipElement = [Link]("totalTip");
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
41
In this step, we're using the [Link]() method to retrieve
references to various HTML elements we'll be interacting with:
● calculateButton: The "Calculate Tip" button.
● billAmountInput: The input field where the user enters the bill amount.
● serviceQualityInput: The dropdown select field where the user selects the
service quality.
● totalTipElement: The paragraph element where we'll display the calculated
tip and total amount.
Step 2: Attach Event Listener
[Link]("click",
calculateTip);
Here, we're attaching an event listener to the "Calculate Tip" button. The
calculateTip function will be called when the button is clicked.
Step 3: Define the calculateTip Function
function calculateTip() {
const billAmount =
parseFloat([Link]);
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
42
const serviceQuality =
parseFloat([Link]);
if (!isNaN(billAmount) && !isNaN(serviceQuality)) {
const tipAmount = billAmount * serviceQuality;
const totalAmount = billAmount + tipAmount;
[Link] = `Tip:
$${[Link](2)} | Total:
$${[Link](2)}`;
} else {
[Link] = "Please enter
valid values.";
}
}
Here's a detailed breakdown of the calculateTip function:
● We start by using parseFloat() to convert the values entered in the
billAmountInput and serviceQualityInput fields from strings to
floating-point numbers. This allows us to perform calculations with them.
● We use isNaN() to check if the entered values are valid numbers. If both the
bill amount and service quality are valid numbers, we proceed with the
calculations. If not, we display an error message in the totalTipElement.
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
43
● Inside the calculation block:
● We calculate the tip amount by multiplying the bill amount by the
service quality. This gives us the tip amount in dollars.
● We calculate the total amount by adding the bill amount and the tip
amount. This gives us the total amount including the tip.
● We use the toFixed(2) method to format the calculated tip and total
amounts to two decimal places, ensuring they look neat and precise.
● Finally, we update the text content of the totalTipElement with the
calculated tip and total amounts, formatted as a string.
Step 4: Testing
When the user clicks the "Calculate Tip" button, the calculateTip function is
executed. It takes the entered bill amount and service quality, calculates the tip
and total amount, and updates the displayed result in the totalTipElement.
This project showcases how JavaScript can be used to interact with user input,
perform calculations, and dynamically update content on a webpage. It's a great
example of a practical application where JavaScript enhances user experience by
providing instant feedback on calculations.
Learn more about Google Apps Scripts with Examples and Source Code Laurence
Svekis Courses [Link]
44