Module VI
Interactivity to a Website
UNIT 1: SCRIPTING LANGUAGE
1.1 Identifying a Scripting Language
A scripting language is a type of programming language that is usually interpreted (not
compiled) and is often used to automate tasks, add interactivity, or control other
software.
Interpreted Language
Code is executed line by line by an interpreter.
You don’t need to convert the code into machine language before running it.
You write → run → see results immediately.
The browser (Chrome, Firefox, etc.) reads code one line at a time.
If there is an error, it stops immediately at that line.
examples: JavaScript, Python, PHP, Ruby.
Compiled Language
Code must be compiled (translated) into machine code before execution.
Once compiled, the program runs very fast.
Examples: C, C++, Java.
Key Characteristics of Scripting Languages
1. Interpreted Execution
Scripting languages run through an interpreter, not a compiler.
This means the code is executed line-by-line.
Example languages: JavaScript, Python, Bash.
2. High-Level Syntax
Easier to read and write.
Uses natural, human-friendly syntax.
o High-level syntax is close to human language, avoiding complex structures.
o It focuses on clarity and simplicity, making the code easier for beginners to
understand and faster for developers to write.
let name = "Sara";
[Link](name);
1
Explanation
1. let name = "Sara";
o let is a keyword used to create (declare) a variable.
o name is the variable’s name.
o "Sara" is a string value (text).
o This line stores the value "Sara" inside the variable name.
2. [Link](name);
o [Link]() is a function used to display output on the browser’s console.
o It prints whatever is inside the parentheses.
o Here, it prints the value stored in name, which is Sara.
Result (Output)
Sara
3. Dynamic Typing
In dynamically typed languages (like JavaScript), you do not need to specify the
data type of a variable when declaring it.
The type can change at runtime, meaning the same variable can hold different types
of data at different moments.
Example : No Type Declaration Needed
let value = 10; // value is a number
[Link](value);
Output:
10
4. Built-in Libraries and Frameworks
Scripting languages often provide ready-made libraries and frameworks that help
developers work faster.
These tools contain pre-written code for common tasks, so developers don’t need to build
everything from scratch.
Why They Are Useful
Save time
Reduce complexity
Make code more reliable
Allow developers to focus on building features instead of solving basic problems
Examples
Python
2
NumPy → used for numerical operations and working with arrays
Pandas → used for data analysis and handling tables/datasets
JavaScript
React → used to build interactive user interfaces
[Link] → allows JavaScript to run on the server
5. Flexibility and Rapid Development
Scripting languages allow developers to write and modify code quickly. They are highly
flexible because they don’t require long setup steps or strict rules.
Common Uses
Prototyping
o Prototyping means creating a quick, working version of a program or feature.
o It helps developers test ideas and see how they work before building the full
application.
o Example in JavaScript:
// Prototype of a simple greeting function
function greet(name) {
[Link]("Hello, " + name + "!");
}
greet("Sara"); // Test if it works
You can test this quickly in a browser console without building a full app.
Automation
o Automation involves writing scripts to perform repetitive tasks
automatically.
This saves time and reduces errors.
Example in Python:
# Automate renaming files in a folder
import os
for i, filename in enumerate([Link]("my_folder")):
[Link](f"my_folder/{filename}", f"my_folder/file_{i}.txt")
Explanation of Output
[Link]("my_folder") → Returns a list of all files in the folder named my_folder.
enumerate(...) → Gives each file an index number (i = 0, 1, 2, …).
3
[Link](...) → Renames each file to the new name format: file_0.txt, file_1.txt, etc.
Example
If my_folder contains:
[Link]
[Link]
[Link]
After running the script, the folder will contain:
file_0.txt
file_1.txt
file_2.txt
Each file is automatically renamed in order, which is very useful for batch renaming or
organizing files.
Common Scripting Languages
JavaScript – Web interactivity
Python – General-purpose scripting
PHP – Server-side scripting
Ruby – Web apps (Ruby on Rails)
Bash – System automation
PowerShell – Windows scripting
1.2 Introduction to JavaScript (JS)
JavaScript is the main language used to make websites interactive.
Interactivity refers to the ability of a website or application to respond to user
actions in real-time.
It makes websites more engaging and user-friendly by allowing users to actively
participate rather than just view static content.
Examples of Interactivity
Users can:
Click buttons → e.g., submit a form or open a pop-up.
Enter data → e.g., type information in forms or search bars.
Trigger animations → e.g., hover effects, slides, or visual transitions.
Open menus → e.g., dropdown or sidebar menus.
Get instant responses → e.g., form validation messages, live notifications.
4
Example in JavaScript
// Display an alert when the button is clicked
[Link]("myButton").onclick = function() {
alert("Button clicked!");
};
Here, clicking the button triggers an immediate response (an alert box).
This demonstrates user interactivity in action.
Code explanation
1. [Link]("myButton")
o document refers to the HTML page.
o getElementById("myButton") searches the HTML page for an element with
the id="myButton".
o This selects the specific button element we want to interact with.
2. .onclick
o This is an event handler.
o It tells the browser: “Do something when this element is clicked.”
3. = function() { ... }
o This defines (a block of code to run when the event occurs).
o Everything inside { ... } will execute when the button is clicked.
4. alert("Button clicked!");
o alert() is a built-in JavaScript function.
o It displays a popup message to the user.
o In this case, it shows "Button clicked!" when the button is clicked.
It Works
1. The browser finds the element with id="myButton".
2. When the user clicks that button, the onclick event triggers.
3. The function runs, showing a popup alert instantly.
1.2.1 Preface of JavaScript
JavaScript was created in 1995 by Brendan Eich.
It is a high-level, interpreted programming language mainly used for web development.
High-level
o Easy for humans to read and write.
o Hides complex machine-level details.
Interpreted
o The browser or runtime executes code line by line without needing
compilation.
5
Used mainly in browsers
o Runs on the client side, directly in web browsers like Chrome, Firefox, and
Edge.
Used to manipulate the DOM (Document Object Model)
o The DOM is a programming interface for web documents.
It represents the structure of an HTML or XML document as a tree of
objects.
Using the DOM, JavaScript can read, modify, and manipulate web page
content and structure dynamically.
o Allows developers to change the content, structure, and style of web pages
dynamically.
o Example: changing text, adding images, or hiding/showing elements based on
user interaction.
Example
// Change the text of an HTML element with id="demo"
[Link]("demo").innerHTML = "Hello, JavaScript!";
Explanation:
[Link]("demo") → selects the element with id="demo"
.innerHTML = "Hello, JavaScript!" → updates its content on the page
Output on the web page:
Hello, JavaScript!
1.2.2 Role of JavaScript in Web Development
JavaScript is a key language for web development. It allows websites to be dynamic,
interactive, and user-friendly.
JavaScript runs inside the web browser, which allows it to control webpage
behavior and make websites interactive.
JavaScript is a versatile programming language that makes websites interactive,
dynamic, and user-friendly. Its main role is to control webpage behavior and
respond to user interactions.
1. Controls Webpage Behavior
JavaScript can change the content, layout, or style of a webpage while it is open in
the browser.
Example: Changing the text of a paragraph or hiding/showing elements without
refreshing the page.
[Link]("demo").innerHTML = "Content updated!";
6
example
<!DOCTYPE html>
<html>
<head>
<title>Demo Example</title>
</head>
<body>
<p id="demo">Original Content</p>
<button onclick="[Link]('demo').innerHTML = 'Content
updated!'">
Click Me
</button>
</body>
</html>
2. Reacts to User Actions
JavaScript responds to user events like clicks, typing, or mouse movements
instantly.
Example: Displaying a message when a button is clicked:
[Link]("btn").onclick = function() {
alert("Button clicked!");
};
3. Updates Content Instantly
Changes are applied immediately, without needing a page reload.
This provides a smooth user experience and reduces server load.
Example: Updating a form’s preview while typing.
4. Client-Side Execution
JavaScript runs directly in the user’s browser (client-side).
It interacts with the DOM (Document Object Model) to modify web page content,
structure, and style dynamically.
It allows websites to respond to user actions in real time.
Example: Changing colors, adding/removing elements, or updating lists
dynamically.
5. Enhances User Experience
Form Validation: Checks user input before sending it to the server.
Animations: Makes websites visually appealing with effects and transitions.
7
API Data Fetching: Retrieves and displays data without reloading the page.
fetch("[Link]
.then(response => [Link]())
.then(data => [Link](data));
6. Server-Side Development ([Link])
JavaScript is not limited to browsers.
Using [Link], it can run on servers, enabling full-stack development with one
language for both client and server.
Example: Building web applications where JavaScript handles both front-end and
back-end logic.
7. Mobile and Desktop Applications
JavaScript can also be used to develop:
o Mobile apps: React Native, NativeScript
o Desktop apps: Electron
o Games: Browser-based or mobile games using frameworks like Phaser
8. Frameworks and Libraries
Libraries and frameworks simplify development and speed up projects.
Examples:
o React, Angular, Vue → Build interactive user interfaces
o jQuery → Simplify DOM manipulation and animations
9. Single Page Applications (SPAs) & Asynchronous Programming
JavaScript allows websites to update content without a full page reload, which
improves speed and user experience.
Asynchronous programming lets web pages fetch data or perform actions in the
background without blocking other operations.
Example: Loading new messages in a chat app without refreshing the page.
Common Uses of JavaScript
1. Form validation
o Checks if user input is correct before sending it to the server.
o Example: ensuring an email field has a valid format.
let email = [Link]("email").value;
if () {
alert("Please enter a valid email address!");
}
8
2. Creating animations
o Move objects, fade elements, or add interactive effects.
[Link]("box").[Link] = "200px";
3. Handling button clicks
o Perform actions when a button is clicked.
[Link]("myButton").onclick = function() {
alert("Button clicked!");
};
4. Fetching data from APIs
o Retrieve data from servers without reloading the page.
fetch("[Link]
.then(response => [Link]())
.then(data => [Link](data));
5. Building full-stack apps (with [Link])
o JavaScript can also run on the server using [Link], enabling developers to
create both the front-end and back-end with one language.
1.2.3 Features of JavaScript
9
1. Object-Centered
JavaScript supports objects, which are collections of key-value pairs.
Objects help organize related data together.
Not fully object-oriented: JavaScript doesn’t enforce classes like Java,
o Object-Oriented Programming (OOP)
o Object-Oriented Programming is a programming paradigm based on objects.
Objects combine data (properties) and functions (methods) to model real-
world entities.
Example:
let student = {
name: "Alem",
age: 17
};
[Link]([Link]); // Output: Alem
[Link]([Link]); // Output: 17
2. Client-Side Technology
Runs on the browser without needing a server.
3. Validation of User Input
Used to check form data before sending it to the server.
Example:
function check() {
let name = [Link]("name").value;
if(name == "")
alert("Name cannot be empty!");
}
4. IF–Else Statements
Used for decision-making.
let age = 18;
if(age >= 18) {
[Link]("Adult");
} else {
[Link]("Minor");
}
5. Interpreter-Based
Runs without compilation.
10
6. Built-in Functions
isNaN("abc"); // true
parseInt("25"); // 25
parseFloat("3.14");
7. Case Sensitive
let Name = "Sara";
let name = "Abel";
These are two different variables.
8. Lightweight
Small amount of memory is needed.
9. Looping
for(let i=1; i<=5; i++){
[Link](i); }
10. Event Handling
<button onclick="greet()">Say Hi</button>
<script>
function greet(){ alert("Hello!"); } </script>
11
1.2.4. Applications of JavaScript (Fully Expanded Explanation)
JavaScript is one of the most important and widely used programming languages in
modern software development. It is used in front-end development, back-end
development, mobile apps, desktop applications, and even game development. Because of
its versatility, JavaScript is considered a must-learn language for all students and
professionals entering the software and web development field.
12
Below are the major applications of JavaScript, explained in detail:
1. Client-Side Validation
Client-side validation means checking the correctness of user inputs before sending the
data to a server.
Saves server time
Reduces unnecessary network requests
Prevents wrong or incomplete data
Provides immediate feedback to users
Example:
When a user fills a form but forgets to enter a name, JavaScript shows a warning without
reloading the page.
function check() {
let name = [Link]("name").value;
if (name == "") {
alert("Name cannot be empty!");
}
}
JavaScript handles this validation instantly in the browser, making websites more
efficient and user-friendly.
2. Manipulating HTML Pages (DOM Manipulation)
JavaScript can dynamically change any part of a webpage by accessing the Document
Object Model (DOM).
Add or delete HTML elements
Change text, images, colors, or styles
Hide and show parts of a webpage
Rearrange layout automatically
Adjust webpage appearance for different screen sizes
13
Example:
[Link]("title").innerHTML = "New Heading!";
This makes websites dynamic rather than static.
3. Dynamic User Notifications
JavaScript can display messages, alerts, pop-ups, and interactive notifications to
communicate with users.
Examples:
Success messages
Error messages
Warning alerts
Confirmation pop-ups
These improve user experience by giving real-time updates or instructions.
4. Back-End Data Loading (AJAX)
AJAX (Asynchronous JavaScript and XML) allows JavaScript to load data from a server in
the background, without refreshing the webpage.
Faster browsing experience
Smooth and interactive webpages
Live content update
Used in search engines, social media, dashboards
Examples of AJAX usage:
Google search suggestions
Live chat systems
Auto-loading more posts on Facebook or Instagram
This improves the speed and smoothness of websites dramatically.
5. Presentations
JavaScript can be used to create web-based slide presentations using libraries like:
RevealJS
BespokeJS
These allow users to create presentations directly in a browser with:
14
Animations
Transitions
Multimedia
CSS styling
This is especially useful for teachers, students, and web-based seminars.
6. Server Applications ([Link])
JavaScript is no longer limited to client-side. With [Link], it can run on servers too.
What [Link] can do:
Build web servers
Create APIs
Handle databases
Build real-time apps (chat, video streaming)
Create command-line tools
[Link] is fast, scalable, and widely used in modern companies like Netflix, Uber,
LinkedIn, and PayPal.
Broader Areas Where JavaScript Is Used
JavaScript has expanded into multiple areas:
Mobile App Development
Using tools like:
React Native
NativeScript
JavaScript can be used to build apps for:
Android
iOS
Tablets
b) Desktop Applications
[Link]
[Link]
JavaScript can create desktop apps like VS Code, Discord, and Slack.
15
c) Game Development
JavaScript libraries allow building browser-based games.
d) Data Visualization
[Link]
[Link]
JavaScript can create data dashboards, graphs, and charts used in business analytics.
Advantages of JavaScript (Fully Detailed)
1. Less Server Interaction
JavaScript can validate data and handle tasks immediately in the browser, reducing the
load on the server.
2. Immediate Feedback
Users get instant results (e.g., "Name required") without waiting for a page reload.
3. Increased Interactivity
JavaScript makes web pages lively and responsive:
Menus
Animations
Buttons
Sliders
Image galleries
4. Richer Interfaces
JavaScript supports advanced UI components:
Drag-and-drop elements
Sliders
Lightboxes
Dynamic forms
This makes websites more professional and user-friendly.
16
Limitations of JavaScript (Fully Explained)
Although powerful, JavaScript has some limitations:
1. Restricted File Access
Client-side JavaScript cannot read or write files on a computer for security reasons.
2. No Multi-Threading
JavaScript normally runs on a single thread, so it cannot perform multiple heavy tasks
simultaneously like some other languages.
3. Lightweight Language
JavaScript is not meant for:
Operating system development
Low-level hardware programming
Heavy computational tasks
It is ideal for web-based interactivity and fast development.
1.2.5 Setting Up the JavaScript Development Environment
JavaScript development requires:
1. A Text Editor / IDE
Editors help you write code easily with:
Syntax highlighting Sublime Text
Auto-completion Atom
Debugging support Eclipse
Recommended editors: WebStorm (paid)
Visual Studio Code (best) Notepad++
2. A Web Browser
Any modern browser can run JavaScript:
Chrome Edge Opera
Firefox Safari
Browsers come with Developer Tools to debug and test JavaScript code.
17
3. Create a Project Directory
A folder to store:
HTML files CSS
JavaScript files Images
4. Create an HTML File
Example:
<!DOCTYPE html>
<html>
<head>
<title>My JavaScript Page</title>
</head>
<body>
</body>
</html>
5. Insert JavaScript Using <script>
You can write JavaScript:
a) Inline
<script>
alert("Hello World!");
</script>
b) External File
<script src="[Link]"></script>
6. Open HTML in Browser
Double-click the HTML file to run and test your JavaScript.
18
1.2.6 Methods to Insert JavaScript in an HTML Document
There are two main ways:
1. Inline Script (Inside HTML File)
You place your JavaScript inside <script> tags:
<script>
[Link]("Hello!");
</script>
These can be written in:
<head>
<body>
HTML5 does not require type="text/javascript" because JavaScript is the default script
type.
2. External JavaScript File
The recommended method.
Example:
<script src="[Link]"></script>
Advantages:
Cleaner HTML
Reusable JS across many pages
Better maintenance
You must place the script file path inside src.
Attributes of the <script> Tag
19
Attribute Meaning and Usage
async <script async> executes the script asynchronously along with the rest
of the page.
Used for fast-loading independent scripts.
defer <script defer> executes the script after the document is parsed and
before firing DOMContentLoaded event.
Script loads in background but executes only after the HTML is fully
parsed. Used for large scripts.
src <script src="uri\path to resource"> specifies the URI/path of an
external script file;
Specifies the external JavaScript file path.
type <script type="text\javascript"> specifies the type of the containing
script e.g.
text\javascript, text\html, text\plain, application\json, application\pdf,
etc.
Defines script type (e.g., text/javascript, application/json). HTML5
default is JavaScript.
crossorigin <script crossorigin="anonymous|use-credentials"> allows error
logging for sites which use a separate domain for static media. Value
anonymous do not send credentials, whereas use-credentials sends the
credentials.
Handles cross-domain permissions.
referrerpolicy <script referrerpolicy="no-referrer"> specifies which referrer
information to send when fetching a script. Values can be no-referrer,
no-referrer-whendowngrade, origin, same-origin, strict-origin, etc.
Controls what referrer information is sent when loading a script.
integrity <script integrity="sha384-oqVuAfXRKap7fdgc"> specifies that a user
agent can use to verify that a fetched resource has been delivered free
of unexpected manipulation.
Ensures a script file hasn’t been modified or tampered with (security
feature).
nomodule <script nomodule> specifies that the script should not be executed in
browsers supporting ES2015 modules.
Prevents script from running in modern browsers that support
modules (used for backward compatibility).
20
Exercise – 10 Marks
Write the following code in your HTML file in VS, run it in the browser, and write the
output you get.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ethiopian International School – Riyadh | JavaScript Module VI</title>
<!-- SCHOOL INFORMATION -->
<meta name="description" content="Ethiopian International School – Riyadh (EISR)
JavaScript Course: Module VI – Interactivity to a Website.">
<style>
body { font-family: Arial, sans-serif; padding: 20px; }
h1, h2, h3 { color: #004080; }
.box {
width: 100px;
height: 100px;
background: orange;
transition: 0.5s;
}
.section {
border: 1px solid #ccc;
padding: 15px;
margin-bottom: 25px;
border-radius: 8px;
}
</style>
<!-- SCRIPT TAG USING "defer" ATTRIBUTE -->
<script defer>
[Link]("Script loaded using defer: Runs after the HTML is parsed.");
</script>
<!-- SCRIPT TAG USING "async" (for demo only) -->
<script async src="[Link]
</head>
<body>
<h1>Ethiopian International School – Riyadh</h1>
<p>
Welcome to the JavaScript Module (Module VI – Interactivity to a Website).
At EISR, students are equipped with modern technological skills needed for the digital
world.
This lesson introduces JavaScript, the primary language for interactive web development.
</p>
<hr>
<!-- ========== 1. SCRIPTING LANGUAGE ============ -->
<div class="section">
<h2>1.1 Identifying a Scripting Language</h2>
21
<p>Scripting languages are interpreted (line-by-line) and used for interactivity and
automation.</p>
<p><b>Example of interpreted JavaScript:</b></p>
<script>
let name = "Sara";
[Link](name);
</script>
</div>
<!-- ======== 2. INTRODUCTION TO JAVASCRIPT ============= -->
<div class="section">
<h2>1.2 Introduction to JavaScript</h2>
<p>JavaScript enables interactivity such as button clicks, animations, and dynamic
content updates.</p>
<button id="myButton">Click me for Interaction</button>
<script>
[Link]("myButton").onclick = function() {
alert("Button clicked! JavaScript Interactivity Example.");
};
</script>
</div>
<!-- ======= 3. ROLE OF JAVASCRIPT ============ -->
<div class="section">
<h2>1.2.2 Role of JavaScript in Web Development</h2>
<p>JavaScript controls webpage behavior, reacts to user actions, and updates content
instantly.</p>
<p id="demo">Original Content</p>
<button onclick="[Link]('demo').innerHTML='Content updated!'">
Update Content
</button>
</div>
<!-- ===== 4. FEATURES OF JAVASCRIPT =============== -->
<div class="section">
<h2>1.2.3 Features of JavaScript</h2>
<h3>1. Object-Centered Example</h3>
<p id="result"></p>
<script>
let student = {
name: "Alem",
age: 17
};
[Link]("result").innerHTML = [Link];
</script>
<h3>2. Validation Example</h3>
<input id="nameField" placeholder="Enter name">
<button onclick="validateName()">Check</button>
<script>
function validateName() {
let n = [Link]("nameField").value;
if (n === "") {
alert("Name cannot be empty!");
22
} else {
alert("Name accepted!");
}
}
</script>
<h3>3. If–Else Example</h3>
<script>
let age = 18;
if (age >= 18) {
[Link]("Adult");
} else {
[Link]("Minor");
}
</script>
<h3>4. Loop Example</h3>
<script>
for (let i = 1; i <= 5; i++) {
[Link]("Loop count:", i);
}
</script>
<h3>5. Built-In Functions</h3>
<p id="output"></p>
<script>
let result1 = isNaN("abc");
let result2 = parseInt("25");
let result3 = parseFloat("3.14");
[Link]("output").innerHTML =
"isNaN(\"abc\") = " + result1 + "<br>" +
"parseInt(\"25\") = " + result2 + "<br>" +
"parseFloat(\"3.14\") = " + result3;
</script>
</div>
<!-- ========= 5. APPLICATIONS OF JAVASCRIPT ============= -->
<div class="section">
<h2>1.2.4 Applications of JavaScript</h2>
<h3>Client-Side Validation</h3>
<p>Instant feedback without server.</p>
<h3>DOM Manipulation</h3>
<p>Click to enlarge the box below.</p>
<div id="box" class="box"></div>
<button onclick="[Link]('box').[Link]='200px'">Grow Box</button>
<h3>AJAX Example (Simulation)</h3>
<script>
fetch("[Link]
.then(res => [Link]())
.then(data => [Link](data))
.catch(error => [Link]("Error:", error));
</script>
</div>
23
<!-- ==== 6. METHODS TO INSERT JAVASCRIPT ======== -->
<div class="section">
<h2>1.2.6 Methods to Insert JavaScript</h2>
<h3>Inline JavaScript</h3>
<button onclick="alert('This is inline JavaScript!')">Inline Script</button>
<h3>External JavaScript File Using <script src></h3>
<p>Example:</p>
<pre>
<script src="[Link]"></script>
</pre>
<h3>Script Tag Attributes Used in Real Web Development</h3>
<ul>
<li><b>async</b> – loads script independently</li>
<li><b>defer</b> – runs after HTML is parsed</li>
<li><b>src</b> – external file path</li>
<li><b>nomodule</b> – disables script in modern browsers</li>
<li><b>integrity</b> – security check hash</li>
<li><b>crossorigin</b> – controls cross-domain access</li>
</ul>
</div>
<!-- DEMO: nomodule -->
<script nomodule>
[Link]("This runs only in old browsers.");
</script>
</body>
</html>
24