JavaScript
Prathab
SYLLABUS
21 Programming for the web
21.1 Programming for the web
For this section of the syllabus, we recommend
that candidates have a working knowledge of
HTML and
css (for example, have studied website
authoring in Cambridge IGCSE Information
and Communication
Technology, syllabus code 0417/0983).
• Using JavaScript to:
– add interactivity to web pages, including by:
○ inserting JavaScript in HTML
○ creating and using external scripts
– change HTML content:
○ text/number, including calculations and
string manipulation
○ images and image properties
– change HTML styles:
○ change style of HTML elements using
document.getElementById(id).style.property =
new style
– show/hide HTML elements using:
○ document.getElementById(id).style.visibility=
○ document.getElementById(id).style.display=
– display data in different ways, including by
writing into:
○ an HTML element, using innerHTML
○ the HTML output using document.write()
○ an alert box, using window.alert()
○ the browser console, using console.log()
– react to common HTML Events, including:
○ onload
– JavaScript loops for iterative methods,
including:
○ for loop
○ for/in loop
○ while loop
○ do/while loop
• Object-based JavaScript programming
techniques and terms, including:
○ JavaScript statements
○ data types (including: number, string,
Boolean, array, object)
○ type conversions
○ variables and arrays
○ JavaScript operators
○ logical operators (AND, OR, NOT)
○ comparison operators (Logical, Ternary,
equal to, equal value and equal type, not
equal to, not
equal value and not equal type, greater
than, less than, greater than or equal to,
less than or
equal to)
○ conditional operators (if, else, else if,
switch)
○ loops
○ break
○ interaction: alert(), prompt(), confirm()
○ functions
○ execution interval methods: setTimeout(),
setInterval()
○ onchange
○ onclick
○ onmouseover
○ onmouseout
○ onkeydown
– provide user interaction using:
○ confirm() and prompt() popups
• The structure and syntax of JavaScript
code, including:
– JavaScript statements composed of:
○ values (literals and variables)
○ operators (assignment, arithmetic,
algebraic, string)
○ comparison (logical, conditional, type)
expressions
○ keywords
○ comments
– functions to be executed:
○ when an event occurs
○ when invoked from code
○ automatically (self-invoked)
– JavaScript timing events, including:
○ execution interval methods
setTimeout() and setInterval()
(continued)
– comments to annotate and explain
code, including:
○ single line and multi-line
️
🏷️Common HTML Tags & Their Descriptions
Tag Description
<!DOCTYPE html> Declares the document type and version of HTML being used.
<html> Wraps the entire HTML document content.
<head> Contains metadata like title, styles, and links to external files.
<title> Sets the title of the web page shown in the browser tab.
<meta> Provides metadata such as character encoding and page description.
<link> Links external files like CSS stylesheets to the HTML document.
<style> Contains internal CSS styles for formatting the page.
<script> Used to include or write JavaScript code for interactivity.
🏷️Common HTML Tags & Their Descriptions
Tag Description
<body> Contains the visible content of the web page.
<h1> to <h6> Define headings, from largest (<h1>) to smallest (<h6>).
<p> Defines a paragraph of text.
<br> Inserts a line break (no closing tag needed).
<hr> Inserts a horizontal line or divider.
<a> Creates a hyperlink to another page or website.
<img> Embeds an image in the page.
<ul> Creates an unordered (bulleted) list.
<ol> Creates an ordered (numbered) list.
🏷️Common HTML Tags & Their Descriptions
Tag Description
<li> Defines a list item inside <ul> or <ol>.
<div> Defines a container for grouping elements and applying styles.
<span> Used to style inline parts of text.
<form> Creates an input form for user data submission.
<input> Inserts fields like text boxes, checkboxes, etc. inside a form.
<label> Defines a label for form input elements.
<button> Creates a clickable button.
🏷️Common HTML Tags & Their Descriptions
Tag Description
<textarea> Provides a multi-line text input field.
<select> Creates a drop-down list.
<option> Defines each option in a drop-down list.
<table> Creates a table structure.
<tr> Defines a table row.
<td> Defines a table data cell.
<th> Defines a table header cell.
JavaScript
JavaScript is a scripting language used to create
interactive and dynamic content on websites.
🌐 What is Interactivity in Web Pages?
• Interactivity in web pages refers to features that allow users to
engage, interact, and respond with the content, rather than just
reading static information. It transforms a webpage from a simple
display into a dynamic, user-driven experience.
What Comes Under Web Page Interactivity?
Feature Description
️
🖱️Clickable Buttons Allow users to trigger actions (e.g., submit, navigate, show/hide content).
📋 Forms Input boxes, dropdowns, checkboxes for user data entry.
🔄 Dynamic Content Updates Content changes without reloading the page (using JavaScript).
✅ Validation Checking form inputs (like email or password) before submission.
🧠 Event Handling Responding to user actions like clicks, typing, hovering.
✨ Animations/Transitions Visual effects triggered by interaction (CSS or JavaScript).
🔀 Interactive Media Play/pause videos, image sliders, audio players.
🔒 Login/Register Systems Authenticating and personalizing user access.
📊 Live Charts/Graphs Updating data visualizations based on user input or API data.
🧭 Navigation Menus Drop-down or collapsible menus that respond to user selection.
Tools Used for Interactivity:
•HTML → Structure
•CSS → Style + Some animations
•JavaScript → Main tool for interactivity
•Frameworks like React, Vue, jQuery → For
advanced interactions
•APIs → Fetching data from servers dynamically
(like live weather or news)
History
• JavaScript was created in 1995 by Brendan Eich at Netscape. Initially
named Mocha, it was later renamed to LiveScript, and finally JavaScript
to capitalize on Java’s popularity. It was first released with Netscape
Navigator 2.0. In 1996, Microsoft introduced a similar version called
JScript in Internet Explorer.
• To standardize the language, ECMAScript was developed and published
by ECMA International in 1997. Over time, JavaScript evolved with
multiple ECMAScript versions, adding features like objects, classes,
modules, and async programming. Today, JavaScript runs on nearly
every web browser and powers interactive websites, server-side
applications (Node.js), mobile apps, and even IoT devices.
Versions of JavaScripts
• ES1 (1997) – First edition, standardization begins.
• ES2 (1998) – Minor editorial changes.
• ES3 (1999) – Added regular expressions, better string handling.
• ES4 – Abandoned due to complexity and disagreement.
• ES5 (2009) – Added JSON support, strict mode, and getters/setters.
• ES6 (2015) (ES2015) – Major update: let, const, arrow functions, classes, modules, promises.
• ES7 (2016) – Includes Array.prototype.includes, ** (exponentiation).
• ES8 (2017) – async/await, object entries/values.
• ES9 (2018) – Rest/spread for objects, asynchronous iteration.
• ES10 (2019) – flat(), flatMap(), optional catch binding.
• ES11 (2020) – Nullish coalescing (??), optional chaining (?.).
• ES12 (2021) – Logical assignment, replaceAll.
• ES13 (2022) – Top-level await, class fields.
• ES14 (2023) – Array find-from-last methods, symbols as keys.
• New versions continue yearly with modern JavaScript features.
How to Install JavaScript Applications on Your
Computer
JavaScript runs directly in any modern browser like:
•Chrome
•Firefox
•Edge
•Safari
You can start writing JavaScript in:
•Your browser’s Developer Console (press F12)
•A text editor like Notepad, VS Code, or Sublime
Text
To Run Advanced JavaScript (Node.js Apps)
If you want to run JavaScript outside the browser (like backend apps or tools),
install Node.js.
✅ How to install Node.js:
1.Go to the official site: https://nodejs.org
2.Download the LTS (Long-Term Support) version.
3.Run the installer.
4.Follow the setup (click "Next", accept license, install).
5.Done! Open Command Prompt and type:
• node -v
• If it shows a version number, Node.js is installed.
What is the cost?
✅ FREE – JavaScript, Node.js, and most tools are open-source and 100%
free.
Setups Required
•Install Node.js (includes NPM – Node Package Manager)
•Use a code editor (like VS Code) for writing code
•Optional: install libraries using commands like:
•npm install express
Notepad, VS Code, or Sublime Text
• Notepad- A very basic text editor that comes pre-installed on
Windows.
• VS Code- A free, powerful, open-source code editor from Microsoft
with extensions.
• Sublime Text- A fast, lightweight text editor with powerful features for
coding.
Comparision
Feature Notepad VS Code Sublime Text
💰 Cost Free Free
Free (with trial); Paid
license ($99)
💻 Coding Support Very Limited
Excellent (extensions,
IntelliSense)
Very Good (fast,
customizable)
🧩 Extensions No Yes (large marketplace) Yes (via Package Control)
🎨 Themes & UI Basic Highly customizable Customizable
⚡ Speed Very Fast
Moderate (depends on
setup)
Extremely Fast
️
🛠️Autocomplete No Yes (smart suggestions) Yes (basic suggestions)
🔄 Multi-cursor Edit No Yes Yes
📁 Project Explorer No Yes Yes
️
🖥️Platforms Windows only Windows, Mac, Linux Windows, Mac, Linux
Adobe Dreamweaver can help in executing
JavaScript
What is Dreamweaver?
• Dreamweaver is a web development tool from Adobe used to design,
code, and preview websites. It supports HTML, CSS, JavaScript, and
more.
How Dreamweaver Helps with JavaScript
Feature Description
🧠 Code Editor
Lets you write JavaScript directly in <script> tags or
external files.
🧩 Syntax Highlighting
Highlights JavaScript keywords, variables, and
functions for easy reading.
🛠️Code Suggestions
Offers autocomplete and code hints to speed up
JavaScript coding.
🔁 Live Preview
Instantly shows how JavaScript behaves in your
webpage without switching browsers.
🔗 File Linking Easily link external JavaScript files to HTML pages.
🧪 Error Checking
Shows basic errors or warnings in your JavaScript
code.
🌐 Browser Integration
You can test the full webpage including JavaScript in
multiple browsers.
Can Dreamweaver run JavaScript?
• ❌ No, Dreamweaver doesn't "execute" JavaScript like Node.js does.
• ✅ It runs JavaScript in the browser as part of the webpage (e.g.,
animations, alerts, DOM manipulations).
• You write JavaScript in Dreamweaver and test it using the Live View or
in your browser.
What Are External Scripts?
External scripts are JavaScript files stored separately (with .js extension) and linked to an HTML
file. This keeps your code organized, reusable, and easier to maintain.
•Link the JavaScript file using <script src="script.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>External Script Example</title>
</head>
<body>
<h1>Click the button</h1>
<button onclick="greetUser()">Greet Me</button>
<!-- Link to the external script file -->
<script src="script.js"></script>
</body>
</html>
📌 Where to Place the <script> Tag?
✅ Best Practice: Place it just before the closing </body> tag to ensure
all HTML is loaded before the script runs.
💡 Advantages of External Scripts:
• ✅ Clean separation of HTML and JavaScript
• ✅ Code reusability across multiple HTML files
• ✅ Easier to debug and maintain
️
🛠️Steps to Create and Use External
Scripts
🔹 Step 1: Create a JavaScript File
1.Open VS Code or any code editor.
2.Create a new file, for example:
script.js
👉
3.Write your JavaScript code in that file:
// script.js
function greetUser() {
alert("Hello, Prathab!");
}
Step 2: Create an HTML File and Link the
Script
•Create a new file: index.html
👉
Use JavaScript to change HTML content,
including:
✅ 1. Change Text Content
<!DOCTYPE html>
<html>
<body>
<p id="message">Original Text</p>
<button onclick="changeText()">Change
Text</button>
<script>
function changeText() {
document.getElementById("message").innerText
= "Hello, Prathab!";
}
</script>
</body>
</html>
✅ 2. Change Number (Simple Calculation)
<!DOCTYPE html>
<html>
<body>
<p id="result">0</p>
<button onclick="calculate()">Calculate 10 +
20</button>
<script>
function calculate() {
let a = 10;
let b = 20;
document.getElementById("result").innerText = a +
b;
}
</script>
</body>
</html>
Use JavaScript to change HTML content,
including:
✅ 3. String Manipulation
<!DOCTYPE html>
<html>
<body>
<p id="name">My name is...</p>
<button onclick="manipulateString()">Show Full
Name</button>
<script>
function manipulateString() {
let firstName = "Prathab";
let middleName = "Yesudhasan";
let lastName = "Singh";
let fullName = firstName + " " + middleName + " " +
lastName;
document.getElementById("name").innerText = "My
name is: " + fullName;
}
</script>
</body>
</html>
✅ 4. Math Calculation Example
<!DOCTYPE html>
<html>
<body>
<p id="area">Area:</p>
<button onclick="calculateArea()">Calculate
Area of Circle (r=5)</button>
<script>
function calculateArea() {
let radius = 5;
let area = Math.PI * radius * radius;
document.getElementById("area").innerText =
"Area: " + area.toFixed(2);
}
</script>
</body>
</html>
JavaScript in Dreamweaver
• You can write this in Dreamweaver, press "Live View," and see the alert in action.
• <!DOCTYPE html>
• <html>
• <head>
• <title>JavaScript Test</title>
• <script>
• function greet() {
• alert("Hello from JavaScript!");
• }
• </script>
• </head>
• <body>
• <button onclick="greet()">Click Me</button>
• </body>
• </html>
Sample program(Normal)
• <!DOCTYPE html>
• <html>
• <head>
• <title>My Page</title>
• </head>
• <body>
• <h1>Hello, world!</h1>
• </body>
• </html>
Sample program(JavaScript)
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<script>
// This script runs when the page loads
alert("Welcome to My Page!");
document.write("<p>This text is written using JavaScript.</p>");
</script>
</head>
<body>
<h1>Hello, world!</h1>
</body>
</html>
document.write in JavaScript
document.write() is a JavaScript method used to write text or HTML directly into a web page.
Syntax:
document.write("Hello, world!");
Example programe:
<!DOCTYPE html>
<html>
<body>
<script>
document.write("<h2>Welcome to JavaScript!</h2>");
</script>
</body>
</html>
<!DOCTYPE html>
<!DOCTYPE html> is a declaration at the very top of an HTML document that tells the browser:
"This is an HTML5 document.“
What is .innerHTML in JavaScript?
.innerHTML is a property in JavaScript that lets you get or set the HTML content inside an element.
✅ Syntax:
// Get content
let content = document.getElementById("elementId").innerHTML;
// Set content
document.getElementById("elementId").innerHTML = "New content here!";
Types of Usage: Get, Set, Dynamic
Type Description Example
Get
Reads the content inside an HTML
element
let text = div.innerHTML;
Set
Replaces existing content with new
HTML or text
div.innerHTML = "<p>Hello</p>";
Dynamic Changes content based on
interaction or input
In buttons, forms, or event-driven
changes
Example Program:
• Initially, the page shows: Hello!
• When the button is clicked, it changes to: You clicked the button!
<!DOCTYPE html>
<html>
<head>
<title>innerHTML Example</title>
</head>
<body>
<h1 id="greeting">Hello!</h1>
<button onclick="changeText()">Click Me</button>
<script>
function changeText() {
document.getElementById("greeting").innerHTML = "You clicked the button!";
}
</script>
</body>
</html>
.innerText vs .textContent
Property .innerText .textContent
Usage Gets or sets the visible text
Gets or sets all text, even hidden
ones
Reads CSS? ✅ Yes (respects display: none) ❌ No (includes hidden elements)
Faster?
❌ Slightly slower (browser
calculates style)
✅ Faster (no layout calculation
needed)
✅ Syntax
// innerText
let text1 = document.getElementById("myElement").innerText;
document.getElementById("myElement").innerText = "Updated text";
// textContent
let text2 = document.getElementById("myElement").textContent;
document.getElementById("myElement").textContent = "Updated content";
Example Program (Both Used):
<!DOCTYPE html>
<html>
<head>
<title>innerText vs textContent</title>
</head>
<body>
<div id="box">Welcome to <span style="display:none">Secret</span> JavaScript!</div>
<p id="output1"></p>
<p id="output2"></p>
<button onclick="showText()">Show innerText and textContent</button>
<script>
function showText() {
let box = document.getElementById("box");
document.getElementById("output1").innerText = "innerText: " + box.innerText;
document.getElementById("output2").innerText = "textContent: " + box.textContent;
}
</script>
</body>
</html>
When button is clicked:
•innerText: Shows only visible content.
•textContent: Shows all, including the hidden "Secret"
document.getElementById in JavaScript
document.getElementById() is a method used to access a specific HTML element using its id attribute.
It allows you to read or modify the content, style, or behavior of that element using JavaScript.
✅ Syntax:
document.getElementById("elementID");
"elementID" → The id of the HTML element you want to access.
Types of Usage:
Type Purpose Example
Get Text Read the content of an element
let text =
document.getElementById("title").i
nnerText;
Set Text Change the content of an element
document.getElementById("title").i
nnerText = "New Title";
Style Change CSS styles
document.getElementById("box").s
tyle.color = "red";
Value Get/set form input values
let name =
document.getElementById("nameI
nput").value;
Event Attach events like click or hover
document.getElementById("btn").o
nclick = function() {}
Example 1: Change Text
<!DOCTYPE html>
<html>
<head>
<title>getElementById Example</title>
</head>
<body>
<h1 id="header">Welcome!</h1>
<button onclick="changeText()">Click Me</button>
<script>
function changeText() {
document.getElementById("header").innerText = "Hello, JavaScript!";
}
</script>
</body>
</html>
Example 2: Change Style
<!DOCTYPE html>
<html>
<body>
<div id="box" style="width:100px; height:100px; background-color:blue;"></div>
<button onclick="changeColor()">Change Color</button>
<script>
function changeColor() {
document.getElementById("box").style.backgroundColor = "green";
}
</script>
</body>
</html>
getElementsByClassName()
•Selects all elements with a given class name.
•Returns a live HTMLCollection (like an array, but not exactly).
•✅ Syntax:
•document.getElementsByClassName("className");
Method Returns Selector Format Use When
getElementsByClassName HTMLCollection (many) Only class name
You want all elements
with a class
querySelector First matching element Any CSS selector
You want just one specific
element
Types of usage:
Type Purpose Example
Read content elements[0].innerText Read the text of the first element
Style change elements[i].style.color = "red" Loop to style all elements
Loop through for (let i=0; i < elements.length; i++) Iterate all matching elements
💻 Example:
<!DOCTYPE html>
<html>
<body>
<p class="greet">Hello!</p>
<p class="greet">Hi there!</p>
<button onclick="changeText()">Change All Greetings</button>
<script>
function changeText() {
let elements = document.getElementsByClassName("greet");
for (let i = 0; i < elements.length; i++) {
elements[i].innerText = "Welcome!";
}
}
</script>
</body>
</html>
querySelector()
• Returns the first element that matches a CSS selector.
• ✅ Syntax:
• document.querySelector("selector");
•Can use IDs, classes, tags (like CSS):
"#id", ".class", "div p", etc.
📘 Types of usage:
Type Purpose Example
Select ID document.querySelector("#box") Select by ID
Select class document.querySelector(".title") First element with that class
Nested tags document.querySelector("div p") First <p> inside a <div>
💻 Example:
<!DOCTYPE html>
<html>
<body>
<h2 class="title">Hello World</h2>
<button onclick="change()">Change First Title</button>
<script>
function change() {
document.querySelector(".title").innerText = "JavaScript Rocks!";
}
</script>
</body>
</html>
<p id="..."> in HTML
•<p> stands for a paragraph element in HTML.
•The id attribute inside it gives a unique name to that specific paragraph so JavaScript or CSS can access,
style, or modify it.
•✅ Syntax:
<p id="myParagraph">This is a paragraph.</p>
Here, myParagraph is the unique identifier (ID) for this paragraph.
•An ID must be unique on the page (no duplicates).
•Use class instead of id when applying styles to multiple elements.
📘 Types of Usage with ID:
Type Purpose Example
Access via JS Modify text, style, etc.
document.getElementById("myPar
agraph")
Style with CSS Apply styles #myParagraph { color: red; }
Anchor link Link to this specific paragraph
<a href="#myParagraph">Go to
Paragraph</a>
💻 Example 1: Change Text with JavaScript
<!DOCTYPE html>
<html>
<body>
<p id="info">This is the original text.</p>
<button onclick="changeText()">Change Text</button>
<script>
function changeText() {
document.getElementById("info").innerText = "This is the new text!";
}
</script>
</body>
</html>
💻 Example 2: Style with CSS using ID
<!DOCTYPE html>
<html>
<head>
<style>
#intro {
color: green;
font-weight: bold;
}
</style>
</head>
<body>
<p id="intro">Welcome to my website!</p>
</body>
</html>
✅ Full Example:HTML program with three paragraphs, and
JavaScript used to write your first, middle, and last names into
each of them:
<!DOCTYPE html>
<html>
<head>
<title>My Name Writer</title>
</head>
<body>
<p id="firstPara"></p>
<p id="secondPara"></p>
<p id="thirdPara"></p>
<script>
// Writing your name parts to the respective paragraphs
document.getElementById("firstPara").innerText = "First Name: Prathab";
document.getElementById("secondPara").innerText = "Middle Name: Yesudhasan";
document.getElementById("thirdPara").innerText = "Last Name: Singh";
</script>
</body>
</html>
Do NOT use .js
•.js is for pure JavaScript files, not for HTML with embedded scripts.
•If you save it as .js, the browser will treat it as a JavaScript file only and won't render any HTML.
Your code:
•Starts with <!DOCTYPE html>
•✅Has <html>, <head>, <body> tags
•✅Includes <script> for JavaScript
•✅So this is a complete HTML document, and you should save it like this:
✅ Example:
File name: name_writer.html
File type: All Files
Encoding (if asked): UTF-8
Programme
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My Name Writer</title>
</head>
<body>
<p id="firstPara"></p>
<p id="secondPara"></p>
<p id="thirdPara"></p>
<script>
// Writing your name parts to the respective paragraphs
document.getElementById("firstPara").innerText = "First Name: Prathab";
document.getElementById("secondPara").innerText = "Middle Name: Yesudhasan";
document.getElementById("thirdPara").innerText = "Last Name: Singh";
</script>
</body>
</html>
Output
📦 What is a Pop-up Box in JavaScript?
• A pop-up box is a built-in browser dialog that shows messages or asks
for input from the user. It appears over the web page and interrupts
normal page flow until it's dismissed.
🧾 Types of Pop-up Boxes in JavaScript
There are three types:
1.alert() – Displays a message with an OK button
2.confirm() – Asks a yes/no question with OK and Cancel
buttons
3.prompt() – Asks the user to input text, with OK and Cancel
buttons
🧩 Syntax
• alert("This is a message!");
• confirm("Are you sure you want to continue?");
• prompt("Please enter your name:");
✅ Example Program
<!DOCTYPE html>
<html>
<head>
<title>Pop-up Box Example</title>
</head>
<body>
<h2>Click the buttons to see pop-up boxes</h2>
<button onclick="showAlert()">Show Alert</button>
<button onclick="showConfirm()">Show Confirm</button>
<button onclick="showPrompt()">Show Prompt</button>
<script>
function showAlert() {
alert("Hello! This is an alert box.");
}
function showConfirm() {
let result = confirm("Do you want to proceed?");
if (result) {
alert("You pressed OK!");
} else {
alert("You pressed Cancel!");
}
}
function showPrompt() {
let name = prompt("What is your name?");
if (name !== null) {
alert("Hello, " + name + "!");
}
}
</script>
</body>
</html>
Output
window.alert(), window.confirm(), and window.prompt() and variables.
Storing results in variables using “var”.
This will give the same output as before, but with a more explicit
approach using window. and variables.
•window.alert() shows a message.
•var userConfirm = window.confirm(...) stores true or false.
•var userName = window.prompt(...) stores the entered text.
Programme for same output
<!DOCTYPE html>
<html>
<head>
<title>Pop-up Boxes with Variables</title>
</head>
<body>
<h2>Click to trigger pop-up boxes</h2>
<button onclick="showBoxes()">Run Pop-ups</button>
<script>
function showBoxes() {
// Alert
window.alert("Hello! This is an alert box.");
// Confirm
var userConfirm = window.confirm("Do you want to proceed?");
if (userConfirm) {
window.alert("You pressed OK!");
} else {
window.alert("You pressed Cancel!");
}
// Prompt
var userName = window.prompt("What is your name?");
if (userName !== null) {
window.alert("Hello, " + userName + "!");
}
}
</script>
</body>
</html>
Worked Example 20.3/Green book
Here is a simple webpage code that:
1.Shows an alert welcoming the user.
2.Asks a confirm question to proceed.
3.Uses prompt to ask a user-defined question.
4.Logs each stage to the browser console.
Programme
<!DOCTYPE html>
<html>
<head>
<title>Interactive Web
Page</title>
</head>
<body>
<h2>Open the browser console to
see logs</h2>
<script>
// Step 1: Show an alert box
welcoming the user
window.alert("Welcome to the
website!");
console.log("Displayed welcome
alert to the user.");
// Step 2: Ask user to confirm
if they want to continue
var proceed = window.confirm("Do
you want to proceed to the
question?");
console.log("User confirmation
requested.");
// Step 3: Check user's choice
if (proceed) {
console.log("User chose to
proceed.");
// Step 4: Ask a question
using prompt
var answer =
window.prompt("What is your
favorite programming
language?");
console.log("Asked user their
favorite programming
language.");
// Optional: Show the answer
back using alert
if (answer !== null) {
window.alert("You entered: " + answer);
console.log("User answered: " +
answer);
} else {
console.log("User canceled the prompt
input.");
}
} else {
console.log("User canceled and chose not
to proceed.");
window.alert("Okay, maybe next time!");
}
</script>
</body>
</html>
Practical Activity 20.2/green book
•Shows an alert saying "Ready to Continue"
•Uses a confirm box and stores the result in a
variable
•Then shows another alert saying "Let's go" if the
user confirms
Programme
<!DOCTYPE html>
<html>
<body>
<script>
// Step 1: Show alert "Ready to Continue"
alert("Ready to Continue");
// Step 2: Confirm box - store user's choice in variable 'decision'
var decision = confirm("Do you want to continue?");
// Step 3: If user clicks OK, show "Let's go"
if (decision) {
alert("Let's go");
} else {
alert("Maybe next time!");
}
</script>
</body>
</html>
Practical Activity 20.3/a,b,c,d/green book
a) your name “Prathab Singh Y” at the top of the page
b) tell a short story using 10 alert() boxes, one after the other.
c) Updated HTML Code with console.log() for Task a & b:
•console.log() lines will appear in the browser’s Developer Console
(press F12 → "Console" tab) to confirm that alerts 1 and 2 were shown.
•Useful for debugging or tracking program flow.
d) Create a basic text web page using HTML,
• Give each element (like paragraphs) a name using id, and
• Use JavaScript to insert the text content into each element instead of
writing it directly in HTML.
a
<!DOCTYPE html>
<html>
<head>
<title>My Name Page</title>
</head>
<body>
<!-- Heading showing your name -->
<h1>Prathab Singh Y</h1>
</body>
</html>
b
<!DOCTYPE html>
<html>
<head>
<title>Story Time</title>
</head>
<body>
<script>
// Story begins here
alert("Once upon a time, in a quiet village, lived a boy named Arjun.");
alert("Arjun was curious and loved exploring the forests near his home.");
alert("One sunny morning, he discovered a hidden cave behind a waterfall.");
alert("Inside the cave, he found glowing stones and ancient markings.");
alert("As he stepped deeper, he heard a faint humming sound.");
alert("To his surprise, he found a tiny dragon trapped behind rocks.");
alert("The dragon looked scared but harmless, and Arjun decided to help.");
alert("With great effort, he moved the rocks and set the dragon free.");
alert("The dragon smiled and gifted Arjun a glowing crystal.");
alert("From that day on, Arjun and the dragon became the best of friends.");
</script>
</body>
</html>
c
<!DOCTYPE html>
<html>
<head>
<title>Story Time with Logs</title>
</head>
<body>
<script>
// Story begins here
alert("Once upon a time, in a quiet village, lived a boy named Arjun.");
console.log("Alert 1: First sentence displayed successfully.");
alert("Arjun was curious and loved exploring the forests near his home.");
console.log("Alert 2: Second sentence displayed successfully.");
alert("One sunny morning, he discovered a hidden cave behind a waterfall.");
alert("Inside the cave, he found glowing stones and ancient markings.");
alert("As he stepped deeper, he heard a faint humming sound.");
alert("To his surprise, he found a tiny dragon trapped behind rocks.");
alert("The dragon looked scared but harmless, and Arjun decided to help.");
alert("With great effort, he moved the rocks and set the dragon free.");
alert("The dragon smiled and gifted Arjun a glowing crystal.");
alert("From that day on, Arjun and the dragon became the best of friends.");
</script>
</body>
</html>
Questions/Pg 474
1. Which keywords will output a box with a
message?
alert("Your message here");
Use: Displays a pop-up box with a message and an
"OK" button.
Example: alert("Welcome to the website!");
Questions/Pg 474
2. Which keywords will write data to the console?
console.log("Your message here");
Use: Writes information to the browser’s
developer console (F12 → Console tab). Used
mainly for debugging.
Example: console.log("Page has loaded
successfully.");
Questions/Pg 474
3. Which keywords will output a new box for
a user to enter data?
prompt("Your question here");
Use: Opens a pop-up with a text input box where the
user can type something.
Example: let name = prompt("What is your name?");
Questions/Pg 474
3. What is the purpose of writing data to the
console?
To check if code is working correctly.
To debug errors or test variable values.
Helps developers trace what’s happening in the program without
disturbing the user.
all three (alert, prompt, console.log) together
<!DOCTYPE html>
<html>
<head>
<title>Interactive Example</title>
</head>
<body>
<h1>Welcome to the Interactive Page</h1>
<script>
// Step 1: Alert to greet the user
alert("Welcome to our website!");
console.log("Alert box displayed: Welcome message");
// Step 2: Prompt to ask for user's name
var userName = prompt("What is your name?");
console.log("Prompt box shown: User entered name - " + userName);
// Step 3: Show another alert using their name
alert("Nice to meet you, " + userName + "!");
console.log("Final alert shown with user's name");
</script>
</body>
</html>
<img id="myImage" src="prathab.jpg" width="300" height="200">
<script>
// Change the image source using JavaScript
document.getElementById("myImage").src = "newimage.jpg";
</script>
getElementById("myImage") targets the image tag, and
.src is used to change the image.
Change an Image Using document.getElementById() in JavaScript
<!-- Basic image --> <img src="prathab.jpg">
<!-- With alternative text --> <img src="prathab.jpg" alt="Prathab's
photo">
<!-- Inside a folder --> <img src="images/prathab.jpg">
<!-- From a website URL -->
<img src="https://example.com/prathab.jpg">
Ways to Use <img src> for prathab.jpg
Attribute Description
src Specifies the image file source
alt Alternate text shown if the image fails to load
width Specifies width of the image (in pixels or %)
height Specifies height of the image
style Used for inline CSS, e.g., style="border:1px solid black;"
border (old) Adds a border (deprecated in HTML5; use CSS instead)
title Tooltip text shown when you hover over the image
loading Lazy-loads the image (lazy, eager)
class / id For styling or JavaScript identification
Common Image Attributes in <img> Tag
Maintaining Aspect Ratio
•If you specify only one of width or height, the
browser maintains the aspect ratio automatically.
<img src="prathab.jpg" width="300"> <!-- height adjusts automatically -->
•Use CSS for more control:
<img src="prathab.jpg" style="aspect-ratio: 3 / 2;">
Practical Activity 20.04/green book
Correct and complete HTML + JavaScript code to
display four images of your favorite animal using
JavaScript. The images will be added using
document.getElementById() method.
Note:
Local file paths like C:UsersHPPictures101.jpg will not work directly in
a browser due to browser security. You need to copy the images to the
same folder as the HTML file or serve them through a local server.
So, place the images 101.jpg, 102.jpg, 103.jpg, and 104.jpg in the same
folder as this HTML file.
Steps
1.Place 101.jpg, 102.jpg, 103.jpg, and 104.jpg in: C:
UsersHPDesktop1234
2.Save the above HTML file (e.g., animal-
gallery.html) in the same folder.
3.Double-click the HTML file to open it in your
browser. The images will display using
JavaScript.
Programme
<!DOCTYPE html>
<html>
<head>
<title>My Favorite Animal Gallery</title>
</head>
<body>
<h1>My Favorite Animal</h1>
<img id="image1" width="300"><br><br>
<img id="image2" width="300"><br><br>
<img id="image3" width="300"><br><br>
<img id="image4" width="300"><br><br>
<script>
// Display four animal images using JavaScript
document.getElementById("image1").src = "101.jpg";
document.getElementById("image2").src = "102.jpg";
document.getElementById("image3").src = "103.jpg";
document.getElementById("image4").src = "104.jpg";
// Console confirmation
console.log("All animal images loaded successfully!");
</script>
</body>
</html>
Practical Activity 20.05/green book
1. Displays your name at the top
2. Shows your photo (B-527D.jpg) when the page loads
3. Displays a story in 4 alert boxes, one after the other
4. Changes the image to 101.jpg, 102.jpg, 103.jpg, and 104.jpg with each alert
box
5. Make sure the following files are placed in C:UsersHPDesktop1234:
6. story-with-images.html (this HTML file)
7. B-527D.jpg, 101.jpg, 102.jpg,103.jpg, 104.jpg
8. Double-click the story-with-images.html file to open it in your browser.
9. Each alert message will change the image automatically!
My picture &my name will come Last
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Story Page - Prathab Singh</title>
</head>
<body>
<!-- Display Name -->
<h1 id="myName">Prathab Singh</h1>
<!-- Display Image -->
<img id="storyImage" src="B-527D.jpg" alt="My Image"
width="300">
<script>
// Log to console that the page has loaded
console.log("Page loaded. Name and image displayed.");
// Array of story sentences
const story = [
"Once upon a time, in a quiet village, lived a brave boy.",
"He loved to explore forests near his home.",
"One day he found a mysterious glowing stone.",
"Suddenly, a magical deer appeared before him.",
"The deer spoke and said it needed help to find its herd.",
"They both ventured deep into the enchanted forest.",
"The boy used the glowing stone to light their path.",
"After a long journey, they found the lost deer
family.",
"The magical deer thanked him and granted a wish.",
"The boy returned home, happy and with a glowing heart."
];
// Array of image names to change (first 4 steps)
const images = ["101.jpg", "102.jpg", "103.jpg",
"104.jpg"];
// Loop through each story part
for (let i = 0; i < story.length; i++) {
alert(story[i]); // Show story part in alert
console.log("Displayed alert: " + story[i]); // Log to
console
// Change image for first 4 parts only
if (i < 4) {
document.getElementById("storyImage").src = images[i];
console.log("Image changed to: " + images[i]);
}
}
</script>
</body>
</html>
My picture &my name will come first
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Story Page - Prathab Singh</title>
</head>
<body>
<!-- Your Name -->
<h1 id="myName">Prathab Singh</h1>
<!-- Your Image -->
<img id="storyImage" src="B-527D.jpg" alt="My Photo" width="300">
<script>
// Run this code only after the page is fully loaded
window.onload = function () {
console.log("Page loaded. Name and initial image displayed.");
// Story text in 10 steps
const story = [
"Once upon a time, in a quiet village, lived a brave boy.",
"He loved to explore forests near his home.",
"One day he found a mysterious glowing stone.",
"Suddenly, a magical deer appeared before him.",
"The deer spoke and said it needed help to find its herd.",
"They both ventured deep into the enchanted forest.",
"The boy used the glowing stone to light their path.",
"After a long journey, they found the lost deer family.",
"The magical deer thanked him and granted a wish.",
"The boy returned home, happy and with a glowing heart."
];
// First 4 images corresponding to 4 story parts
const images = ["101.jpg", "102.jpg", "103.jpg", "104.jpg"];
// Show story one by one with image changes
for (let i = 0; i < story.length; i++) {
alert(story[i]); // Show alert box
console.log("Displayed alert: " + story[i]);
// Change image for the first 4 story steps
if (i < 4) {
document.getElementById("storyImage").src = images[i];
console.log("Image changed to: " + images[i]);
}
}
};
</script>
</body>
</html>
JavaScript running before the browser finishes rendering the
HTML content. When alert() is called too early, it pauses the page
load, so the elements like your name and photo don't appear before the
alerts begin.
1. Wait until the entire HTML body is loaded before running the
script.
2. Use the window.onload event to ensure the name and your image
are displayed before starting the alert story.
To fix this and actually see each image change with
each alert, you need to use delayed execution. That
means using setTimeout() to:
•Show an alert
•Change the image
•Wait a second or two
•Then go to the next alert and image
Final Programme
1. Your name Prathab Singh will appear at the top immediately when the page loads.
2. Your photo (B-527D.jpg) will also appear before the first alert box.
3. Then, each alert box will display a sentence in the story and also change the image based on
that part of the story.
4. Make sure all the image files (B-527D.jpg, 101.jpg, etc.) are copied and placed in the same
folder as your .html file.
Final correct Programme
<!DOCTYPE html>
<html>
<head>
<title>Story with Images</title>
</head>
<body>
<h1 id="name">Prathab Singh</h1>
<img id="storyImage" src="B-527D.jpg" width="400" />
<script>
const messages = [
"Once upon a time, in a quiet village, there was a
brave boy.",
"He always dreamed of exploring the forest.",
"One day, he packed his bag and set off.",
"In the woods, he saw a mysterious light.",
"He followed the light and found a magical cave.",
"Inside the cave, he met a talking bird.",
"The bird gave him a golden key.",
"The key opened a secret door in the mountain.",
"Behind the door, he found a treasure chest.",
"He returned home as a hero!"
];
const images = [
"101.jpg",
"102.jpg",
"103.jpg",
"104.jpg"
];
function showStoryPart(i) {
if (i < messages.length) {
if (i < images.length) {
document.getElementById("storyImage").src =
images[i];
}
setTimeout(() => {
alert(messages[i]);
showStoryPart(i + 1);
}, 500);
}
}
window.onload = () => {
// Ensure the name and initial image are visible
first
setTimeout(() => {
showStoryPart(0);
}, 500);
};
</script>
</body>
</html>
1. CSS Styling for Images:Make images
️ 🖼️
responsive, rounded, or with shadows.
img {
width: 100%;
border-radius: 10px;
box-shadow: 5px 5px 10px gray;
}
2. Image Change on Mouse Hover.
🖼️
<img src="normal.jpg"
onmouseover="this.src='hover.jpg'"
onmouseout="this.src='normal.jpg'" />
3. Image Slider or Carousel
🖼️
Learn how to automatically change images every few seconds
like a slideshow using setInterval().
4. 🧠 Preloading Images
const img1 = new Image();
img1.src = "101.jpg";
4. 📁 Dynamic Image Loading from a Folder
(Advanced)
Use JavaScript or even server-side languages like PHP to load images
dynamically from a folder (if building bigger projects).
6. Click to Change Image
👆
<img id="pic" src="101.jpg" onclick="nextImage()" />
<script>
const images = ["101.jpg", "102.jpg", "103.jpg"];
let index = 0;
function nextImage() {
index = (index + 1) % images.length;
document.getElementById("pic").src = images[index];
}
</script>
•Thank You

01_JavaScript_Advanced Level_Pratahb.pptx

  • 1.
  • 2.
    SYLLABUS 21 Programming forthe web 21.1 Programming for the web For this section of the syllabus, we recommend that candidates have a working knowledge of HTML and css (for example, have studied website authoring in Cambridge IGCSE Information and Communication Technology, syllabus code 0417/0983). • Using JavaScript to: – add interactivity to web pages, including by: ○ inserting JavaScript in HTML ○ creating and using external scripts – change HTML content: ○ text/number, including calculations and string manipulation ○ images and image properties – change HTML styles: ○ change style of HTML elements using document.getElementById(id).style.property = new style – show/hide HTML elements using: ○ document.getElementById(id).style.visibility= ○ document.getElementById(id).style.display= – display data in different ways, including by writing into: ○ an HTML element, using innerHTML ○ the HTML output using document.write() ○ an alert box, using window.alert() ○ the browser console, using console.log() – react to common HTML Events, including: ○ onload – JavaScript loops for iterative methods, including: ○ for loop ○ for/in loop ○ while loop ○ do/while loop • Object-based JavaScript programming techniques and terms, including: ○ JavaScript statements ○ data types (including: number, string, Boolean, array, object) ○ type conversions ○ variables and arrays ○ JavaScript operators ○ logical operators (AND, OR, NOT) ○ comparison operators (Logical, Ternary, equal to, equal value and equal type, not equal to, not equal value and not equal type, greater than, less than, greater than or equal to, less than or equal to) ○ conditional operators (if, else, else if, switch) ○ loops ○ break ○ interaction: alert(), prompt(), confirm() ○ functions ○ execution interval methods: setTimeout(), setInterval() ○ onchange ○ onclick ○ onmouseover ○ onmouseout ○ onkeydown – provide user interaction using: ○ confirm() and prompt() popups • The structure and syntax of JavaScript code, including: – JavaScript statements composed of: ○ values (literals and variables) ○ operators (assignment, arithmetic, algebraic, string) ○ comparison (logical, conditional, type) expressions ○ keywords ○ comments – functions to be executed: ○ when an event occurs ○ when invoked from code ○ automatically (self-invoked) – JavaScript timing events, including: ○ execution interval methods setTimeout() and setInterval() (continued) – comments to annotate and explain code, including: ○ single line and multi-line
  • 3.
    ️ 🏷️Common HTML Tags& Their Descriptions Tag Description <!DOCTYPE html> Declares the document type and version of HTML being used. <html> Wraps the entire HTML document content. <head> Contains metadata like title, styles, and links to external files. <title> Sets the title of the web page shown in the browser tab. <meta> Provides metadata such as character encoding and page description. <link> Links external files like CSS stylesheets to the HTML document. <style> Contains internal CSS styles for formatting the page. <script> Used to include or write JavaScript code for interactivity.
  • 4.
    🏷️Common HTML Tags& Their Descriptions Tag Description <body> Contains the visible content of the web page. <h1> to <h6> Define headings, from largest (<h1>) to smallest (<h6>). <p> Defines a paragraph of text. <br> Inserts a line break (no closing tag needed). <hr> Inserts a horizontal line or divider. <a> Creates a hyperlink to another page or website. <img> Embeds an image in the page. <ul> Creates an unordered (bulleted) list. <ol> Creates an ordered (numbered) list.
  • 5.
    🏷️Common HTML Tags& Their Descriptions Tag Description <li> Defines a list item inside <ul> or <ol>. <div> Defines a container for grouping elements and applying styles. <span> Used to style inline parts of text. <form> Creates an input form for user data submission. <input> Inserts fields like text boxes, checkboxes, etc. inside a form. <label> Defines a label for form input elements. <button> Creates a clickable button.
  • 6.
    🏷️Common HTML Tags& Their Descriptions Tag Description <textarea> Provides a multi-line text input field. <select> Creates a drop-down list. <option> Defines each option in a drop-down list. <table> Creates a table structure. <tr> Defines a table row. <td> Defines a table data cell. <th> Defines a table header cell.
  • 7.
    JavaScript JavaScript is ascripting language used to create interactive and dynamic content on websites.
  • 8.
    🌐 What isInteractivity in Web Pages? • Interactivity in web pages refers to features that allow users to engage, interact, and respond with the content, rather than just reading static information. It transforms a webpage from a simple display into a dynamic, user-driven experience.
  • 9.
    What Comes UnderWeb Page Interactivity? Feature Description ️ 🖱️Clickable Buttons Allow users to trigger actions (e.g., submit, navigate, show/hide content). 📋 Forms Input boxes, dropdowns, checkboxes for user data entry. 🔄 Dynamic Content Updates Content changes without reloading the page (using JavaScript). ✅ Validation Checking form inputs (like email or password) before submission. 🧠 Event Handling Responding to user actions like clicks, typing, hovering. ✨ Animations/Transitions Visual effects triggered by interaction (CSS or JavaScript). 🔀 Interactive Media Play/pause videos, image sliders, audio players. 🔒 Login/Register Systems Authenticating and personalizing user access. 📊 Live Charts/Graphs Updating data visualizations based on user input or API data. 🧭 Navigation Menus Drop-down or collapsible menus that respond to user selection.
  • 10.
    Tools Used forInteractivity: •HTML → Structure •CSS → Style + Some animations •JavaScript → Main tool for interactivity •Frameworks like React, Vue, jQuery → For advanced interactions •APIs → Fetching data from servers dynamically (like live weather or news)
  • 11.
    History • JavaScript wascreated in 1995 by Brendan Eich at Netscape. Initially named Mocha, it was later renamed to LiveScript, and finally JavaScript to capitalize on Java’s popularity. It was first released with Netscape Navigator 2.0. In 1996, Microsoft introduced a similar version called JScript in Internet Explorer. • To standardize the language, ECMAScript was developed and published by ECMA International in 1997. Over time, JavaScript evolved with multiple ECMAScript versions, adding features like objects, classes, modules, and async programming. Today, JavaScript runs on nearly every web browser and powers interactive websites, server-side applications (Node.js), mobile apps, and even IoT devices.
  • 12.
    Versions of JavaScripts •ES1 (1997) – First edition, standardization begins. • ES2 (1998) – Minor editorial changes. • ES3 (1999) – Added regular expressions, better string handling. • ES4 – Abandoned due to complexity and disagreement. • ES5 (2009) – Added JSON support, strict mode, and getters/setters. • ES6 (2015) (ES2015) – Major update: let, const, arrow functions, classes, modules, promises. • ES7 (2016) – Includes Array.prototype.includes, ** (exponentiation). • ES8 (2017) – async/await, object entries/values. • ES9 (2018) – Rest/spread for objects, asynchronous iteration. • ES10 (2019) – flat(), flatMap(), optional catch binding. • ES11 (2020) – Nullish coalescing (??), optional chaining (?.). • ES12 (2021) – Logical assignment, replaceAll. • ES13 (2022) – Top-level await, class fields. • ES14 (2023) – Array find-from-last methods, symbols as keys. • New versions continue yearly with modern JavaScript features.
  • 13.
    How to InstallJavaScript Applications on Your Computer JavaScript runs directly in any modern browser like: •Chrome •Firefox •Edge •Safari
  • 14.
    You can startwriting JavaScript in: •Your browser’s Developer Console (press F12) •A text editor like Notepad, VS Code, or Sublime Text
  • 15.
    To Run AdvancedJavaScript (Node.js Apps) If you want to run JavaScript outside the browser (like backend apps or tools), install Node.js. ✅ How to install Node.js: 1.Go to the official site: https://nodejs.org 2.Download the LTS (Long-Term Support) version. 3.Run the installer. 4.Follow the setup (click "Next", accept license, install). 5.Done! Open Command Prompt and type: • node -v • If it shows a version number, Node.js is installed.
  • 16.
    What is thecost? ✅ FREE – JavaScript, Node.js, and most tools are open-source and 100% free.
  • 17.
    Setups Required •Install Node.js(includes NPM – Node Package Manager) •Use a code editor (like VS Code) for writing code •Optional: install libraries using commands like: •npm install express
  • 18.
    Notepad, VS Code,or Sublime Text • Notepad- A very basic text editor that comes pre-installed on Windows. • VS Code- A free, powerful, open-source code editor from Microsoft with extensions. • Sublime Text- A fast, lightweight text editor with powerful features for coding.
  • 19.
    Comparision Feature Notepad VSCode Sublime Text 💰 Cost Free Free Free (with trial); Paid license ($99) 💻 Coding Support Very Limited Excellent (extensions, IntelliSense) Very Good (fast, customizable) 🧩 Extensions No Yes (large marketplace) Yes (via Package Control) 🎨 Themes & UI Basic Highly customizable Customizable ⚡ Speed Very Fast Moderate (depends on setup) Extremely Fast ️ 🛠️Autocomplete No Yes (smart suggestions) Yes (basic suggestions) 🔄 Multi-cursor Edit No Yes Yes 📁 Project Explorer No Yes Yes ️ 🖥️Platforms Windows only Windows, Mac, Linux Windows, Mac, Linux
  • 20.
    Adobe Dreamweaver canhelp in executing JavaScript What is Dreamweaver? • Dreamweaver is a web development tool from Adobe used to design, code, and preview websites. It supports HTML, CSS, JavaScript, and more.
  • 21.
    How Dreamweaver Helpswith JavaScript Feature Description 🧠 Code Editor Lets you write JavaScript directly in <script> tags or external files. 🧩 Syntax Highlighting Highlights JavaScript keywords, variables, and functions for easy reading. 🛠️Code Suggestions Offers autocomplete and code hints to speed up JavaScript coding. 🔁 Live Preview Instantly shows how JavaScript behaves in your webpage without switching browsers. 🔗 File Linking Easily link external JavaScript files to HTML pages. 🧪 Error Checking Shows basic errors or warnings in your JavaScript code. 🌐 Browser Integration You can test the full webpage including JavaScript in multiple browsers.
  • 22.
    Can Dreamweaver runJavaScript? • ❌ No, Dreamweaver doesn't "execute" JavaScript like Node.js does. • ✅ It runs JavaScript in the browser as part of the webpage (e.g., animations, alerts, DOM manipulations). • You write JavaScript in Dreamweaver and test it using the Live View or in your browser.
  • 23.
    What Are ExternalScripts? External scripts are JavaScript files stored separately (with .js extension) and linked to an HTML file. This keeps your code organized, reusable, and easier to maintain. •Link the JavaScript file using <script src="script.js"></script> <!DOCTYPE html> <html> <head> <title>External Script Example</title> </head> <body> <h1>Click the button</h1> <button onclick="greetUser()">Greet Me</button> <!-- Link to the external script file --> <script src="script.js"></script> </body> </html> 📌 Where to Place the <script> Tag? ✅ Best Practice: Place it just before the closing </body> tag to ensure all HTML is loaded before the script runs. 💡 Advantages of External Scripts: • ✅ Clean separation of HTML and JavaScript • ✅ Code reusability across multiple HTML files • ✅ Easier to debug and maintain ️ 🛠️Steps to Create and Use External Scripts 🔹 Step 1: Create a JavaScript File 1.Open VS Code or any code editor. 2.Create a new file, for example: script.js 👉 3.Write your JavaScript code in that file: // script.js function greetUser() { alert("Hello, Prathab!"); } Step 2: Create an HTML File and Link the Script •Create a new file: index.html 👉
  • 24.
    Use JavaScript tochange HTML content, including: ✅ 1. Change Text Content <!DOCTYPE html> <html> <body> <p id="message">Original Text</p> <button onclick="changeText()">Change Text</button> <script> function changeText() { document.getElementById("message").innerText = "Hello, Prathab!"; } </script> </body> </html> ✅ 2. Change Number (Simple Calculation) <!DOCTYPE html> <html> <body> <p id="result">0</p> <button onclick="calculate()">Calculate 10 + 20</button> <script> function calculate() { let a = 10; let b = 20; document.getElementById("result").innerText = a + b; } </script> </body> </html>
  • 25.
    Use JavaScript tochange HTML content, including: ✅ 3. String Manipulation <!DOCTYPE html> <html> <body> <p id="name">My name is...</p> <button onclick="manipulateString()">Show Full Name</button> <script> function manipulateString() { let firstName = "Prathab"; let middleName = "Yesudhasan"; let lastName = "Singh"; let fullName = firstName + " " + middleName + " " + lastName; document.getElementById("name").innerText = "My name is: " + fullName; } </script> </body> </html> ✅ 4. Math Calculation Example <!DOCTYPE html> <html> <body> <p id="area">Area:</p> <button onclick="calculateArea()">Calculate Area of Circle (r=5)</button> <script> function calculateArea() { let radius = 5; let area = Math.PI * radius * radius; document.getElementById("area").innerText = "Area: " + area.toFixed(2); } </script> </body> </html>
  • 26.
    JavaScript in Dreamweaver •You can write this in Dreamweaver, press "Live View," and see the alert in action. • <!DOCTYPE html> • <html> • <head> • <title>JavaScript Test</title> • <script> • function greet() { • alert("Hello from JavaScript!"); • } • </script> • </head> • <body> • <button onclick="greet()">Click Me</button> • </body> • </html>
  • 27.
    Sample program(Normal) • <!DOCTYPEhtml> • <html> • <head> • <title>My Page</title> • </head> • <body> • <h1>Hello, world!</h1> • </body> • </html>
  • 28.
    Sample program(JavaScript) <!DOCTYPE html> <html> <head> <title>MyPage</title> <script> // This script runs when the page loads alert("Welcome to My Page!"); document.write("<p>This text is written using JavaScript.</p>"); </script> </head> <body> <h1>Hello, world!</h1> </body> </html>
  • 29.
    document.write in JavaScript document.write()is a JavaScript method used to write text or HTML directly into a web page. Syntax: document.write("Hello, world!"); Example programe: <!DOCTYPE html> <html> <body> <script> document.write("<h2>Welcome to JavaScript!</h2>"); </script> </body> </html>
  • 30.
    <!DOCTYPE html> <!DOCTYPE html>is a declaration at the very top of an HTML document that tells the browser: "This is an HTML5 document.“
  • 31.
    What is .innerHTMLin JavaScript? .innerHTML is a property in JavaScript that lets you get or set the HTML content inside an element. ✅ Syntax: // Get content let content = document.getElementById("elementId").innerHTML; // Set content document.getElementById("elementId").innerHTML = "New content here!";
  • 32.
    Types of Usage:Get, Set, Dynamic Type Description Example Get Reads the content inside an HTML element let text = div.innerHTML; Set Replaces existing content with new HTML or text div.innerHTML = "<p>Hello</p>"; Dynamic Changes content based on interaction or input In buttons, forms, or event-driven changes
  • 33.
    Example Program: • Initially,the page shows: Hello! • When the button is clicked, it changes to: You clicked the button! <!DOCTYPE html> <html> <head> <title>innerHTML Example</title> </head> <body> <h1 id="greeting">Hello!</h1> <button onclick="changeText()">Click Me</button> <script> function changeText() { document.getElementById("greeting").innerHTML = "You clicked the button!"; } </script> </body> </html>
  • 34.
    .innerText vs .textContent Property.innerText .textContent Usage Gets or sets the visible text Gets or sets all text, even hidden ones Reads CSS? ✅ Yes (respects display: none) ❌ No (includes hidden elements) Faster? ❌ Slightly slower (browser calculates style) ✅ Faster (no layout calculation needed) ✅ Syntax // innerText let text1 = document.getElementById("myElement").innerText; document.getElementById("myElement").innerText = "Updated text"; // textContent let text2 = document.getElementById("myElement").textContent; document.getElementById("myElement").textContent = "Updated content";
  • 35.
    Example Program (BothUsed): <!DOCTYPE html> <html> <head> <title>innerText vs textContent</title> </head> <body> <div id="box">Welcome to <span style="display:none">Secret</span> JavaScript!</div> <p id="output1"></p> <p id="output2"></p> <button onclick="showText()">Show innerText and textContent</button> <script> function showText() { let box = document.getElementById("box"); document.getElementById("output1").innerText = "innerText: " + box.innerText; document.getElementById("output2").innerText = "textContent: " + box.textContent; } </script> </body> </html> When button is clicked: •innerText: Shows only visible content. •textContent: Shows all, including the hidden "Secret"
  • 36.
    document.getElementById in JavaScript document.getElementById()is a method used to access a specific HTML element using its id attribute. It allows you to read or modify the content, style, or behavior of that element using JavaScript. ✅ Syntax: document.getElementById("elementID"); "elementID" → The id of the HTML element you want to access.
  • 37.
    Types of Usage: TypePurpose Example Get Text Read the content of an element let text = document.getElementById("title").i nnerText; Set Text Change the content of an element document.getElementById("title").i nnerText = "New Title"; Style Change CSS styles document.getElementById("box").s tyle.color = "red"; Value Get/set form input values let name = document.getElementById("nameI nput").value; Event Attach events like click or hover document.getElementById("btn").o nclick = function() {}
  • 38.
    Example 1: ChangeText <!DOCTYPE html> <html> <head> <title>getElementById Example</title> </head> <body> <h1 id="header">Welcome!</h1> <button onclick="changeText()">Click Me</button> <script> function changeText() { document.getElementById("header").innerText = "Hello, JavaScript!"; } </script> </body> </html>
  • 39.
    Example 2: ChangeStyle <!DOCTYPE html> <html> <body> <div id="box" style="width:100px; height:100px; background-color:blue;"></div> <button onclick="changeColor()">Change Color</button> <script> function changeColor() { document.getElementById("box").style.backgroundColor = "green"; } </script> </body> </html>
  • 40.
    getElementsByClassName() •Selects all elementswith a given class name. •Returns a live HTMLCollection (like an array, but not exactly). •✅ Syntax: •document.getElementsByClassName("className"); Method Returns Selector Format Use When getElementsByClassName HTMLCollection (many) Only class name You want all elements with a class querySelector First matching element Any CSS selector You want just one specific element
  • 41.
    Types of usage: TypePurpose Example Read content elements[0].innerText Read the text of the first element Style change elements[i].style.color = "red" Loop to style all elements Loop through for (let i=0; i < elements.length; i++) Iterate all matching elements
  • 42.
    💻 Example: <!DOCTYPE html> <html> <body> <pclass="greet">Hello!</p> <p class="greet">Hi there!</p> <button onclick="changeText()">Change All Greetings</button> <script> function changeText() { let elements = document.getElementsByClassName("greet"); for (let i = 0; i < elements.length; i++) { elements[i].innerText = "Welcome!"; } } </script> </body> </html>
  • 43.
    querySelector() • Returns thefirst element that matches a CSS selector. • ✅ Syntax: • document.querySelector("selector"); •Can use IDs, classes, tags (like CSS): "#id", ".class", "div p", etc.
  • 44.
    📘 Types ofusage: Type Purpose Example Select ID document.querySelector("#box") Select by ID Select class document.querySelector(".title") First element with that class Nested tags document.querySelector("div p") First <p> inside a <div>
  • 45.
    💻 Example: <!DOCTYPE html> <html> <body> <h2class="title">Hello World</h2> <button onclick="change()">Change First Title</button> <script> function change() { document.querySelector(".title").innerText = "JavaScript Rocks!"; } </script> </body> </html>
  • 46.
    <p id="..."> inHTML •<p> stands for a paragraph element in HTML. •The id attribute inside it gives a unique name to that specific paragraph so JavaScript or CSS can access, style, or modify it. •✅ Syntax: <p id="myParagraph">This is a paragraph.</p> Here, myParagraph is the unique identifier (ID) for this paragraph. •An ID must be unique on the page (no duplicates). •Use class instead of id when applying styles to multiple elements.
  • 47.
    📘 Types ofUsage with ID: Type Purpose Example Access via JS Modify text, style, etc. document.getElementById("myPar agraph") Style with CSS Apply styles #myParagraph { color: red; } Anchor link Link to this specific paragraph <a href="#myParagraph">Go to Paragraph</a>
  • 48.
    💻 Example 1:Change Text with JavaScript <!DOCTYPE html> <html> <body> <p id="info">This is the original text.</p> <button onclick="changeText()">Change Text</button> <script> function changeText() { document.getElementById("info").innerText = "This is the new text!"; } </script> </body> </html>
  • 49.
    💻 Example 2:Style with CSS using ID <!DOCTYPE html> <html> <head> <style> #intro { color: green; font-weight: bold; } </style> </head> <body> <p id="intro">Welcome to my website!</p> </body> </html>
  • 50.
    ✅ Full Example:HTMLprogram with three paragraphs, and JavaScript used to write your first, middle, and last names into each of them: <!DOCTYPE html> <html> <head> <title>My Name Writer</title> </head> <body> <p id="firstPara"></p> <p id="secondPara"></p> <p id="thirdPara"></p> <script> // Writing your name parts to the respective paragraphs document.getElementById("firstPara").innerText = "First Name: Prathab"; document.getElementById("secondPara").innerText = "Middle Name: Yesudhasan"; document.getElementById("thirdPara").innerText = "Last Name: Singh"; </script> </body> </html>
  • 51.
    Do NOT use.js •.js is for pure JavaScript files, not for HTML with embedded scripts. •If you save it as .js, the browser will treat it as a JavaScript file only and won't render any HTML. Your code: •Starts with <!DOCTYPE html> •✅Has <html>, <head>, <body> tags •✅Includes <script> for JavaScript •✅So this is a complete HTML document, and you should save it like this: ✅ Example: File name: name_writer.html File type: All Files Encoding (if asked): UTF-8
  • 52.
    Programme <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>MyName Writer</title> </head> <body> <p id="firstPara"></p> <p id="secondPara"></p> <p id="thirdPara"></p> <script> // Writing your name parts to the respective paragraphs document.getElementById("firstPara").innerText = "First Name: Prathab"; document.getElementById("secondPara").innerText = "Middle Name: Yesudhasan"; document.getElementById("thirdPara").innerText = "Last Name: Singh"; </script> </body> </html>
  • 53.
  • 54.
    📦 What isa Pop-up Box in JavaScript? • A pop-up box is a built-in browser dialog that shows messages or asks for input from the user. It appears over the web page and interrupts normal page flow until it's dismissed.
  • 55.
    🧾 Types ofPop-up Boxes in JavaScript There are three types: 1.alert() – Displays a message with an OK button 2.confirm() – Asks a yes/no question with OK and Cancel buttons 3.prompt() – Asks the user to input text, with OK and Cancel buttons
  • 56.
    🧩 Syntax • alert("Thisis a message!"); • confirm("Are you sure you want to continue?"); • prompt("Please enter your name:");
  • 57.
    ✅ Example Program <!DOCTYPEhtml> <html> <head> <title>Pop-up Box Example</title> </head> <body> <h2>Click the buttons to see pop-up boxes</h2> <button onclick="showAlert()">Show Alert</button> <button onclick="showConfirm()">Show Confirm</button> <button onclick="showPrompt()">Show Prompt</button> <script> function showAlert() { alert("Hello! This is an alert box."); } function showConfirm() { let result = confirm("Do you want to proceed?"); if (result) { alert("You pressed OK!"); } else { alert("You pressed Cancel!"); } } function showPrompt() { let name = prompt("What is your name?"); if (name !== null) { alert("Hello, " + name + "!"); } } </script> </body> </html>
  • 58.
  • 59.
    window.alert(), window.confirm(), andwindow.prompt() and variables. Storing results in variables using “var”. This will give the same output as before, but with a more explicit approach using window. and variables. •window.alert() shows a message. •var userConfirm = window.confirm(...) stores true or false. •var userName = window.prompt(...) stores the entered text.
  • 60.
    Programme for sameoutput <!DOCTYPE html> <html> <head> <title>Pop-up Boxes with Variables</title> </head> <body> <h2>Click to trigger pop-up boxes</h2> <button onclick="showBoxes()">Run Pop-ups</button> <script> function showBoxes() { // Alert window.alert("Hello! This is an alert box."); // Confirm var userConfirm = window.confirm("Do you want to proceed?"); if (userConfirm) { window.alert("You pressed OK!"); } else { window.alert("You pressed Cancel!"); } // Prompt var userName = window.prompt("What is your name?"); if (userName !== null) { window.alert("Hello, " + userName + "!"); } } </script> </body> </html>
  • 62.
    Worked Example 20.3/Greenbook Here is a simple webpage code that: 1.Shows an alert welcoming the user. 2.Asks a confirm question to proceed. 3.Uses prompt to ask a user-defined question. 4.Logs each stage to the browser console.
  • 63.
    Programme <!DOCTYPE html> <html> <head> <title>Interactive Web Page</title> </head> <body> <h2>Openthe browser console to see logs</h2> <script> // Step 1: Show an alert box welcoming the user window.alert("Welcome to the website!"); console.log("Displayed welcome alert to the user."); // Step 2: Ask user to confirm if they want to continue var proceed = window.confirm("Do you want to proceed to the question?"); console.log("User confirmation requested."); // Step 3: Check user's choice if (proceed) { console.log("User chose to proceed."); // Step 4: Ask a question using prompt var answer = window.prompt("What is your favorite programming language?"); console.log("Asked user their favorite programming language."); // Optional: Show the answer back using alert if (answer !== null) { window.alert("You entered: " + answer); console.log("User answered: " + answer); } else { console.log("User canceled the prompt input."); } } else { console.log("User canceled and chose not to proceed."); window.alert("Okay, maybe next time!"); } </script> </body> </html>
  • 65.
    Practical Activity 20.2/greenbook •Shows an alert saying "Ready to Continue" •Uses a confirm box and stores the result in a variable •Then shows another alert saying "Let's go" if the user confirms
  • 66.
    Programme <!DOCTYPE html> <html> <body> <script> // Step1: Show alert "Ready to Continue" alert("Ready to Continue"); // Step 2: Confirm box - store user's choice in variable 'decision' var decision = confirm("Do you want to continue?"); // Step 3: If user clicks OK, show "Let's go" if (decision) { alert("Let's go"); } else { alert("Maybe next time!"); } </script> </body> </html>
  • 68.
    Practical Activity 20.3/a,b,c,d/greenbook a) your name “Prathab Singh Y” at the top of the page b) tell a short story using 10 alert() boxes, one after the other. c) Updated HTML Code with console.log() for Task a & b: •console.log() lines will appear in the browser’s Developer Console (press F12 → "Console" tab) to confirm that alerts 1 and 2 were shown. •Useful for debugging or tracking program flow. d) Create a basic text web page using HTML, • Give each element (like paragraphs) a name using id, and • Use JavaScript to insert the text content into each element instead of writing it directly in HTML.
  • 69.
    a <!DOCTYPE html> <html> <head> <title>My NamePage</title> </head> <body> <!-- Heading showing your name --> <h1>Prathab Singh Y</h1> </body> </html>
  • 70.
    b <!DOCTYPE html> <html> <head> <title>Story Time</title> </head> <body> <script> //Story begins here alert("Once upon a time, in a quiet village, lived a boy named Arjun."); alert("Arjun was curious and loved exploring the forests near his home."); alert("One sunny morning, he discovered a hidden cave behind a waterfall."); alert("Inside the cave, he found glowing stones and ancient markings."); alert("As he stepped deeper, he heard a faint humming sound."); alert("To his surprise, he found a tiny dragon trapped behind rocks."); alert("The dragon looked scared but harmless, and Arjun decided to help."); alert("With great effort, he moved the rocks and set the dragon free."); alert("The dragon smiled and gifted Arjun a glowing crystal."); alert("From that day on, Arjun and the dragon became the best of friends."); </script> </body> </html>
  • 72.
    c <!DOCTYPE html> <html> <head> <title>Story Timewith Logs</title> </head> <body> <script> // Story begins here alert("Once upon a time, in a quiet village, lived a boy named Arjun."); console.log("Alert 1: First sentence displayed successfully."); alert("Arjun was curious and loved exploring the forests near his home."); console.log("Alert 2: Second sentence displayed successfully."); alert("One sunny morning, he discovered a hidden cave behind a waterfall."); alert("Inside the cave, he found glowing stones and ancient markings."); alert("As he stepped deeper, he heard a faint humming sound."); alert("To his surprise, he found a tiny dragon trapped behind rocks."); alert("The dragon looked scared but harmless, and Arjun decided to help."); alert("With great effort, he moved the rocks and set the dragon free."); alert("The dragon smiled and gifted Arjun a glowing crystal."); alert("From that day on, Arjun and the dragon became the best of friends."); </script> </body> </html>
  • 74.
    Questions/Pg 474 1. Whichkeywords will output a box with a message? alert("Your message here"); Use: Displays a pop-up box with a message and an "OK" button. Example: alert("Welcome to the website!");
  • 75.
    Questions/Pg 474 2. Whichkeywords will write data to the console? console.log("Your message here"); Use: Writes information to the browser’s developer console (F12 → Console tab). Used mainly for debugging. Example: console.log("Page has loaded successfully.");
  • 76.
    Questions/Pg 474 3. Whichkeywords will output a new box for a user to enter data? prompt("Your question here"); Use: Opens a pop-up with a text input box where the user can type something. Example: let name = prompt("What is your name?");
  • 77.
    Questions/Pg 474 3. Whatis the purpose of writing data to the console? To check if code is working correctly. To debug errors or test variable values. Helps developers trace what’s happening in the program without disturbing the user.
  • 78.
    all three (alert,prompt, console.log) together <!DOCTYPE html> <html> <head> <title>Interactive Example</title> </head> <body> <h1>Welcome to the Interactive Page</h1> <script> // Step 1: Alert to greet the user alert("Welcome to our website!"); console.log("Alert box displayed: Welcome message"); // Step 2: Prompt to ask for user's name var userName = prompt("What is your name?"); console.log("Prompt box shown: User entered name - " + userName); // Step 3: Show another alert using their name alert("Nice to meet you, " + userName + "!"); console.log("Final alert shown with user's name"); </script> </body> </html>
  • 80.
    <img id="myImage" src="prathab.jpg"width="300" height="200"> <script> // Change the image source using JavaScript document.getElementById("myImage").src = "newimage.jpg"; </script> getElementById("myImage") targets the image tag, and .src is used to change the image. Change an Image Using document.getElementById() in JavaScript
  • 81.
    <!-- Basic image--> <img src="prathab.jpg"> <!-- With alternative text --> <img src="prathab.jpg" alt="Prathab's photo"> <!-- Inside a folder --> <img src="images/prathab.jpg"> <!-- From a website URL --> <img src="https://example.com/prathab.jpg"> Ways to Use <img src> for prathab.jpg
  • 82.
    Attribute Description src Specifiesthe image file source alt Alternate text shown if the image fails to load width Specifies width of the image (in pixels or %) height Specifies height of the image style Used for inline CSS, e.g., style="border:1px solid black;" border (old) Adds a border (deprecated in HTML5; use CSS instead) title Tooltip text shown when you hover over the image loading Lazy-loads the image (lazy, eager) class / id For styling or JavaScript identification Common Image Attributes in <img> Tag
  • 83.
    Maintaining Aspect Ratio •Ifyou specify only one of width or height, the browser maintains the aspect ratio automatically. <img src="prathab.jpg" width="300"> <!-- height adjusts automatically --> •Use CSS for more control: <img src="prathab.jpg" style="aspect-ratio: 3 / 2;">
  • 84.
    Practical Activity 20.04/greenbook Correct and complete HTML + JavaScript code to display four images of your favorite animal using JavaScript. The images will be added using document.getElementById() method. Note: Local file paths like C:UsersHPPictures101.jpg will not work directly in a browser due to browser security. You need to copy the images to the same folder as the HTML file or serve them through a local server. So, place the images 101.jpg, 102.jpg, 103.jpg, and 104.jpg in the same folder as this HTML file.
  • 85.
    Steps 1.Place 101.jpg, 102.jpg,103.jpg, and 104.jpg in: C: UsersHPDesktop1234 2.Save the above HTML file (e.g., animal- gallery.html) in the same folder. 3.Double-click the HTML file to open it in your browser. The images will display using JavaScript.
  • 86.
    Programme <!DOCTYPE html> <html> <head> <title>My FavoriteAnimal Gallery</title> </head> <body> <h1>My Favorite Animal</h1> <img id="image1" width="300"><br><br> <img id="image2" width="300"><br><br> <img id="image3" width="300"><br><br> <img id="image4" width="300"><br><br> <script> // Display four animal images using JavaScript document.getElementById("image1").src = "101.jpg"; document.getElementById("image2").src = "102.jpg"; document.getElementById("image3").src = "103.jpg"; document.getElementById("image4").src = "104.jpg"; // Console confirmation console.log("All animal images loaded successfully!"); </script> </body> </html>
  • 87.
    Practical Activity 20.05/greenbook 1. Displays your name at the top 2. Shows your photo (B-527D.jpg) when the page loads 3. Displays a story in 4 alert boxes, one after the other 4. Changes the image to 101.jpg, 102.jpg, 103.jpg, and 104.jpg with each alert box 5. Make sure the following files are placed in C:UsersHPDesktop1234: 6. story-with-images.html (this HTML file) 7. B-527D.jpg, 101.jpg, 102.jpg,103.jpg, 104.jpg 8. Double-click the story-with-images.html file to open it in your browser. 9. Each alert message will change the image automatically!
  • 88.
    My picture &myname will come Last <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Story Page - Prathab Singh</title> </head> <body> <!-- Display Name --> <h1 id="myName">Prathab Singh</h1> <!-- Display Image --> <img id="storyImage" src="B-527D.jpg" alt="My Image" width="300"> <script> // Log to console that the page has loaded console.log("Page loaded. Name and image displayed."); // Array of story sentences const story = [ "Once upon a time, in a quiet village, lived a brave boy.", "He loved to explore forests near his home.", "One day he found a mysterious glowing stone.", "Suddenly, a magical deer appeared before him.", "The deer spoke and said it needed help to find its herd.", "They both ventured deep into the enchanted forest.", "The boy used the glowing stone to light their path.", "After a long journey, they found the lost deer family.", "The magical deer thanked him and granted a wish.", "The boy returned home, happy and with a glowing heart." ]; // Array of image names to change (first 4 steps) const images = ["101.jpg", "102.jpg", "103.jpg", "104.jpg"]; // Loop through each story part for (let i = 0; i < story.length; i++) { alert(story[i]); // Show story part in alert console.log("Displayed alert: " + story[i]); // Log to console // Change image for first 4 parts only if (i < 4) { document.getElementById("storyImage").src = images[i]; console.log("Image changed to: " + images[i]); } } </script> </body> </html>
  • 89.
    My picture &myname will come first <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Story Page - Prathab Singh</title> </head> <body> <!-- Your Name --> <h1 id="myName">Prathab Singh</h1> <!-- Your Image --> <img id="storyImage" src="B-527D.jpg" alt="My Photo" width="300"> <script> // Run this code only after the page is fully loaded window.onload = function () { console.log("Page loaded. Name and initial image displayed."); // Story text in 10 steps const story = [ "Once upon a time, in a quiet village, lived a brave boy.", "He loved to explore forests near his home.", "One day he found a mysterious glowing stone.", "Suddenly, a magical deer appeared before him.", "The deer spoke and said it needed help to find its herd.", "They both ventured deep into the enchanted forest.", "The boy used the glowing stone to light their path.", "After a long journey, they found the lost deer family.", "The magical deer thanked him and granted a wish.", "The boy returned home, happy and with a glowing heart." ]; // First 4 images corresponding to 4 story parts const images = ["101.jpg", "102.jpg", "103.jpg", "104.jpg"]; // Show story one by one with image changes for (let i = 0; i < story.length; i++) { alert(story[i]); // Show alert box console.log("Displayed alert: " + story[i]); // Change image for the first 4 story steps if (i < 4) { document.getElementById("storyImage").src = images[i]; console.log("Image changed to: " + images[i]); } } }; </script> </body> </html>
  • 90.
    JavaScript running beforethe browser finishes rendering the HTML content. When alert() is called too early, it pauses the page load, so the elements like your name and photo don't appear before the alerts begin. 1. Wait until the entire HTML body is loaded before running the script. 2. Use the window.onload event to ensure the name and your image are displayed before starting the alert story.
  • 91.
    To fix thisand actually see each image change with each alert, you need to use delayed execution. That means using setTimeout() to: •Show an alert •Change the image •Wait a second or two •Then go to the next alert and image
  • 92.
    Final Programme 1. Yourname Prathab Singh will appear at the top immediately when the page loads. 2. Your photo (B-527D.jpg) will also appear before the first alert box. 3. Then, each alert box will display a sentence in the story and also change the image based on that part of the story. 4. Make sure all the image files (B-527D.jpg, 101.jpg, etc.) are copied and placed in the same folder as your .html file.
  • 93.
    Final correct Programme <!DOCTYPEhtml> <html> <head> <title>Story with Images</title> </head> <body> <h1 id="name">Prathab Singh</h1> <img id="storyImage" src="B-527D.jpg" width="400" /> <script> const messages = [ "Once upon a time, in a quiet village, there was a brave boy.", "He always dreamed of exploring the forest.", "One day, he packed his bag and set off.", "In the woods, he saw a mysterious light.", "He followed the light and found a magical cave.", "Inside the cave, he met a talking bird.", "The bird gave him a golden key.", "The key opened a secret door in the mountain.", "Behind the door, he found a treasure chest.", "He returned home as a hero!" ]; const images = [ "101.jpg", "102.jpg", "103.jpg", "104.jpg" ]; function showStoryPart(i) { if (i < messages.length) { if (i < images.length) { document.getElementById("storyImage").src = images[i]; } setTimeout(() => { alert(messages[i]); showStoryPart(i + 1); }, 500); } } window.onload = () => { // Ensure the name and initial image are visible first setTimeout(() => { showStoryPart(0); }, 500); }; </script> </body> </html>
  • 94.
    1. CSS Stylingfor Images:Make images ️ 🖼️ responsive, rounded, or with shadows. img { width: 100%; border-radius: 10px; box-shadow: 5px 5px 10px gray; }
  • 95.
    2. Image Changeon Mouse Hover. 🖼️ <img src="normal.jpg" onmouseover="this.src='hover.jpg'" onmouseout="this.src='normal.jpg'" />
  • 96.
    3. Image Slideror Carousel 🖼️ Learn how to automatically change images every few seconds like a slideshow using setInterval().
  • 97.
    4. 🧠 PreloadingImages const img1 = new Image(); img1.src = "101.jpg";
  • 98.
    4. 📁 DynamicImage Loading from a Folder (Advanced) Use JavaScript or even server-side languages like PHP to load images dynamically from a folder (if building bigger projects).
  • 99.
    6. Click toChange Image 👆 <img id="pic" src="101.jpg" onclick="nextImage()" /> <script> const images = ["101.jpg", "102.jpg", "103.jpg"]; let index = 0; function nextImage() { index = (index + 1) % images.length; document.getElementById("pic").src = images[index]; } </script>
  • 100.