Jul 15, 2024
Instructor: Anam Khan, Let's Subgrade
index.html
) and a JavaScript file (app.js
).<script src="app.js"></script>
.<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fortune Teller</title>
</head>
<body>
<h1>What's Your Future?</h1>
<p>Enter your favorite color:</p>
<input type="text" id="favColor">
<button onclick="tellFortune()">Tell Me</button>
<p id="fortune"></p>
<script src="app.js"></script>
</body>
</html>
function tellFortune() {
let favColor = document.getElementById('favColor').value;
let career;
if (favColor === 'red') {
career = 'You might be a passionate leader';
} else if (favColor === 'green') {
career = 'The world of creativity awaits you';
} else if (favColor === 'blue') {
career = 'You have the potential to be a problem solver';
} else {
career = 'The future holds many exciting surprises for you!';
}
document.getElementById('fortune').innerHTML = career;
}
<!DOCTYPE html>
, <html>
, <head>
, <body>
, <title>
, and form elements (<input>
and <button>
).<script src="app.js"></script>
to link an external JavaScript file.tellFortune()
, uses document.getElementById
to fetch input value, and conditional statements (if-else
) for logic.onclick="tellFortune()"
is used to call the tellFortune
function on button click.var
, let
, and const
for variable declarations.let
and const
introduced after ES6 (2015).const
is used for variables that do not change.let
is used for variables that can change.var
is older practice and less commonly used post ES6.function
keyword followed by function name and parentheses.if
, else if
, and else
used for decision making.if (condition) { // code }
.else if
and else
to handle multiple conditions and default cases.==
) vs Triple equals (===
).==
checks for value equality, may perform type conversion.===
checks for both value and type equality, no type conversion.document.getElementById()
to fetch elements from the DOM.innerHTML
to change the content of HTML elements dynamically.Next session preview: Building a Rock-Paper-Scissors game using JavaScript.