0% found this document useful (0 votes)
2 views17 pages

Chapter-3

Chapter 3 covers the fundamentals of web programming, including the distinction between the Web and the Internet, the purpose of websites, and the functionality of web applications. It explains the development process of websites, the differences between static and dynamic sites, and introduces HTML as the markup language for web content. Additionally, it discusses the importance of search engines and the client-server model in web communication.

Uploaded by

najafzehra77
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views17 pages

Chapter-3

Chapter 3 covers the fundamentals of web programming, including the distinction between the Web and the Internet, the purpose of websites, and the functionality of web applications. It explains the development process of websites, the differences between static and dynamic sites, and introduces HTML as the markup language for web content. Additionally, it discusses the importance of search engines and the client-server model in web communication.

Uploaded by

najafzehra77
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CHAPTER 3

Programming Fundamentals
Chapter Notes

3.1 Introduction to Web & Websites

3.1.1 What is the Web (World Wide Web / WWW)?


The World Wide Web (WWW), commonly called the Web, is a system of interlinked documents, images,
videos, and other resources that are accessed through the Internet using web browsers. It was invented by
Tim Berners-Lee in 1989 while working at CERN. The Web is not the same as the Internet — the Internet
is the global network of interconnected computers, while the Web is a service that runs on top of the
Internet, allowing information to be shared through hyperlinks and URLs (Uniform Resource Locators).

The Web works on a client-server model using the HTTP/HTTPS protocol. When a person types a web
address into a browser, the browser sends a request to a web server, and the server responds by sending
back the requested web page, which the browser then displays.

Example: Typing [Link] in a browser sends a request over the Internet to Google's servers,
which respond with the HTML, CSS and JavaScript files needed to display the Google search page.

3.1.2 Web Pages vs. Websites


A web page is a single document written in HTML that can be viewed in a browser. A website, on the
other hand, is a collection of related web pages linked together, usually sharing a common domain name
and navigation structure.

Aspect Web Page Website


Definition A single HTML document. A collection of linked web pages.
Scope One screen/URL of content. Multiple pages under one
domain.
Example The "About Us" page of a The entire company site (Home,
company. About, Contact, etc.).
Navigation May contain links to other pages. Provides a menu/navigation
system connecting all pages.
3.1.3 Purpose of Websites
Websites are created for many purposes, and understanding these purposes helps in planning the design,
content, and technology used to build them:

• Information sharing — e.g., news portals, educational sites, government portals.


• Business and e-commerce — selling products/services online (e.g., Amazon, Daraz).
• Communication and social interaction — social networking sites (e.g., Facebook, LinkedIn).
• Entertainment — streaming platforms, gaming sites, blogs.
• Branding and marketing — building an organization's online identity and credibility.
• Providing services — online banking, booking systems, and web applications.

3.1.4 Search Engines


A search engine is a software system designed to search the Web for information based on keywords
entered by a user, and to return a ranked list of relevant results. Common examples include Google, Bing,
and Yahoo.

Search engines work in three major stages:

• Crawling — automated programs called "crawlers" or "spiders" browse the Web and follow
hyperlinks to discover new and updated pages.
• Indexing — the content of discovered pages is analyzed and stored in a massive database (the index),
organized by keywords, topics, and metadata.
• Ranking/Retrieval — when a user submits a query, the search engine's ranking algorithm scores
indexed pages for relevance and displays the best matches in order, often within milliseconds.

Note: Search Engine Optimization (SEO) refers to techniques used by website owners to improve how
highly their pages rank in search engine results.

3.2 Web Applications

3.2.1 Definition and Key Features


A web application (web app) is a software program that runs on a web server and is accessed through a
web browser, but unlike a simple website, it allows users to interact with data, perform tasks, and receive
dynamic, personalized responses rather than just reading static content.

Key features of web applications include:

• Interactivity — users can input data, submit forms, and receive processed results (e.g., online
banking, webmail).
• Data processing — the app performs calculations or logic on the server or client side (e.g., adding
items to a shopping cart).
• Database connectivity — most web apps read from and write to a database to store user data.
• User accounts and authentication — login systems, sessions, and personalized dashboards.
• Cross-platform access — runs in any device with a browser, without needing installation.
Examples: Gmail, Google Docs, online banking portals, e-commerce checkout systems, and project
management tools like Trello.

3.2.2 Difference Between a Regular Website and a Web Application


Aspect Regular Website Web Application
Purpose Primarily provides information. Allows users to perform tasks and
interact with data.
Content Mostly static or lightly dynamic Highly dynamic, data-driven
content. content.
User interaction Limited (reading, browsing, Extensive (forms, calculations,
clicking links). transactions).
Example A restaurant's information site An online food ordering and
(menu, hours). payment system.

3.2.3 How a Web Browser Communicates with a Web Server


Communication between a browser (client) and a web server follows the Client-Server Model over the
HTTP/HTTPS protocol. The general process is as follows:

• The user enters a URL or clicks a link in the browser.


• The browser resolves the domain name to an IP address using the Domain Name System (DNS).
• The browser sends an HTTP request (e.g., GET or POST) to the web server at that IP address.
• The web server processes the request — retrieving files, or running server-side code and querying a
database if needed.
• The server sends back an HTTP response, which includes a status code (e.g., 200 OK, 404 Not Found)
and the requested content (HTML, CSS, JS, images, etc.).
• The browser renders the received content and displays the web page to the user.

Note: This request-response cycle repeats every time a user navigates to a new page, submits a form,
or an AJAX/JavaScript request fetches new data without reloading the whole page.
3.3 Website Development

3.3.1 Basics of Website Creation and the Development Process


Website development is the process of building, creating, and maintaining websites. It typically follows a
structured lifecycle:

• Planning — defining the website's purpose, target audience, and required features.
• Designing — creating wireframes and visual mock-ups (layout, colour scheme, typography).
• Development/Coding — writing the actual HTML, CSS, JavaScript, and server-side code.
• Testing — checking for bugs, broken links, cross-browser compatibility, and responsiveness.
• Deployment — publishing the website to a live web server (hosting).
• Maintenance — regularly updating content, fixing issues, and improving performance/security.

3.3.2 Front-end Development vs. Back-end Development


Website development is generally divided into two major areas that work together to deliver a complete
web experience:

Front-end development: also called "client-side" development, refers to everything the user sees and
directly interacts with in the browser — layout, design, buttons, forms, and animations. It is built using
HTML, CSS, and JavaScript.

Back-end development: also called "server-side" development, refers to the behind-the-scenes logic that
powers a website — handling requests, processing data, managing databases, and enforcing business rules.
It is built using server-side languages such as PHP, Python, [Link], Java, or C#, along with databases
like MySQL or MongoDB.

Aspect Front-end Development Back-end Development


Runs on The user's browser (client side). The web server (server side).
Focus Look, feel, and user interaction. Data processing, logic, and
storage.
Technologies HTML, CSS, JavaScript. PHP, Python, [Link], databases
(SQL/NoSQL).
Visible to user? Yes, directly. No, works invisibly behind the
scenes.
3.4 Static Websites

3.4.1 Definition, Characteristics, and Examples


A static website is a website consisting of fixed content that is delivered to the user's browser exactly as
stored, without being generated or altered by a server at the time of the request. Every visitor sees the
same content unless the developer manually edits the underlying files.

Characteristics of static websites:

• Built using only HTML and CSS (sometimes with a little JavaScript for simple effects).
• Content does not change based on user input or database queries.
• Pages load quickly because the server simply sends existing files without extra processing.
• Simple and inexpensive to host, since no server-side processing or database is required.
Examples: A personal portfolio page, a small business "brochure" site with contact information, or a
simple event landing page.

3.4.2 Use Cases and Limitations


Use cases: static websites are ideal for informational sites that rarely change, such as personal résumés,
documentation pages, small business profile sites, and simple landing pages for marketing campaigns.

Limitations: static websites cannot easily provide personalized content, user logins, real-time data, or
interactive features such as shopping carts. Any content update requires manually editing the HTML
file(s), which becomes difficult to manage as the website grows.

3.5 Dynamic Websites

3.5.1 Definition, Characteristics, and Differences from Static Websites


A dynamic website is a website whose content can change automatically based on factors such as user
interaction, time, database records, or user preferences. The content is generated in real time by server-
side scripts (e.g., PHP, [Link], Python) that often pull data from a database before sending the finished
page to the browser.
Aspect Static Website Dynamic Website
Content Fixed; same for every visitor. Changes based on data, user, or
time.
Technology HTML & CSS only. HTML/CSS/JS plus server-side
languages and databases.
Update process Manual editing of source files. Automatic, via database updates
or admin panels.
Examples Portfolio site, simple landing page. Facebook, Amazon, online
banking, blogs with CMS.

3.5.2 Features of Dynamic Websites


• User-specific content — showing different information to different logged-in users (e.g., "Welcome,
Ali" and a personalized news feed).
• Interactivity — forms, comment sections, live search suggestions, and shopping carts.
• Database integration — content such as products, articles, or user posts is stored in and retrieved from
a database.
• Content Management Systems (CMS) — platforms like WordPress allow non-technical users to
add/update content easily.

3.5.3 Why Website Owners Prefer Dynamic Websites


Businesses and organizations often prefer dynamic websites because they enable greater user engagement
and personalization. Dynamic sites can greet returning users by name, recommend products based on
browsing history, allow customers to leave reviews or comments, and let administrators update content
without touching code. This flexibility improves user experience, increases the time users spend on the
site, and supports business growth through features like online transactions and analytics.

3.6 HTML (HyperText Markup Language)

3.6.1 Introduction to HTML and Its Uses


HTML (HyperText Markup Language) is the standard markup language used to create the structure and
content of web pages. HTML uses a system of "tags" (enclosed in angle brackets, e.g. <p>) to define
elements such as headings, paragraphs, links, images, and other content that a browser then renders
visually.
HTML is not a programming language — it does not perform logic or calculations — but rather a markup
language that describes how content should be organized and displayed. HTML works together with CSS
(for styling/appearance) and JavaScript (for behaviour/interactivity) to build complete, functional web
pages.

3.6.2 Installing and Using an Editor (Visual Studio Code)


While HTML files can technically be written in any plain text editor (like Notepad), professional
developers use a code editor such as Visual Studio Code (VS Code) because it provides syntax
highlighting, auto-completion, error detection, and useful extensions (e.g., Live Server for instantly
previewing pages in a browser).

Basic steps to get started with VS Code for HTML:

• Download and install VS Code from the official website ([Link]).


• Create a new folder for your project and open it in VS Code.
• Create a new file with the extension .html (e.g., [Link]).
• Type ! and press Tab (Emmet shortcut) to auto-generate a basic HTML boilerplate structure.
• Install the "Live Server" extension to view live changes in the browser as you type.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My First Page</title>
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>

3.6.3 HTML Document Object Model (DOM)


The Document Object Model (DOM) is a programming interface and tree-like structure that represents an
HTML document. When a browser loads an HTML page, it converts the HTML into the DOM — a
hierarchy of "nodes" (elements, attributes, and text) that can be accessed and manipulated, typically using
JavaScript.

The DOM hierarchy generally looks like this:

• Document (the root)


◦ html (root element)
◦ head (contains metadata, title, links to CSS/JS)
◦ body (contains visible content: headings, paragraphs, images, etc.)
Because the DOM represents the page as a tree of objects, JavaScript can find any element (a "node") and
change its text, style, or attributes dynamically — this is the foundation of interactive web pages.

Note: Understanding the DOM is essential before learning JavaScript, since almost all JavaScript
interactivity works by selecting and modifying DOM nodes (e.g., [Link]()).

3.6.4 Basic HTML Tags and Elements


HTML provides a wide variety of tags to structure content. The most commonly used ones are:

Tag Purpose Example


<h1> to <h6> Headings, from most important (h1) to <h1>Chapter Title</h1>
least (h6).
<p> Defines a paragraph of text. <p>This is a paragraph.</p>
<a> Creates a hyperlink to another page or <ahref="[Link]">Next
resource. Page</a>
<img> Embeds an image (self-closing tag). <imgsrc="[Link]" alt="Logo">
<ul>/<ol>/<li> Unordered / ordered lists and list items. <ul><li>Item 1</li></ul>
<table> Defines a data table. <table>...</table>
<div> A generic block-level container for <div class="box">...</div>
grouping content.
<span> A generic inline container for styling <span
text. class="highlight">text</span>

A short example combining several basic tags:

<h1>Welcome to My Website</h1>
<p>This site is about learning <strong>HTML</strong>.</p>
<a href="[Link] [Link]</a>
<img src="[Link]" alt="A sample photo">
<ul>
<li>Introduction</li>
<li>Basics</li>
<li>Advanced Topics</li>
</ul>
3.6.5 Manipulating Data with Tables
HTML tables are used to display data in a structured, row-and-column format using the <table>, <tr>
(table row), <th> (table header cell) and <td> (table data cell) tags.

<table border="1">
<tr>
<th>Name</th>
<th>Subject</th>
<th>Marks</th>
</tr>
<tr>
<td>Ali</td>
<td>Computer Science</td>
<td>85</td>
</tr>
<tr>
<td>Sara</td>
<td>Mathematics</td>
<td>92</td>
</tr>
</table>
Additional attributes such as colspan and rowspan allow a single cell to span multiple columns or rows,
which is useful for creating merged headers or grouped data — a technique frequently used when
"manipulating" or reorganizing tabular data for clearer presentation.

3.6.6 Adding Resources (Links, Images, Video Clips)


HTML allows external and internal resources to be embedded directly into a web page:

Links: created with the <a> (anchor) tag and the href attribute, which can point to another page, an
external website, an email address ([Link] or a specific section of the same page (using an id and #).

Images: embedded with the <img> tag; the src attribute specifies the image file path/URL, and the alt
attribute provides alternate text for accessibility and for cases where the image fails to load.

Video clips: embedded using the <video> tag with a src attribute or nested <source> tags, along with
attributes such as controls (to show play/pause controls), autoplay, and loop.

<a href="[Link] to Wikipedia</a>


<img src="images/[Link]" alt="A forest landscape" width="400">

<video width="400" controls>


<source src="movie.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>

3.7 Cascading Style Sheets (CSS)

3.7.1 Introduction to CSS and Its Purpose


CSS (Cascading Style Sheets) is a stylesheet language used to control the visual presentation of HTML
content — including colours, fonts, spacing, layout, and positioning. While HTML defines the structure
and meaning of content, CSS defines how that content looks. The name "cascading" refers to the way
styling rules can come from multiple sources and "cascade" down, with more specific rules overriding
more general ones based on a defined priority system.

A basic CSS rule consists of a selector (which HTML element(s) to style) and a declaration block (the
properties and values to apply):

selector {
property: value;
property: value;
}

/* Example */
h1 {
color: navy;
font-size: 32px;
}

3.7.2 Types of CSS


[Link] Inline CSS
Inline CSS is applied directly to a single HTML element using its style attribute. It affects only that
specific element and has the highest priority in the cascade, but it is not reusable and mixes styling with
content, making it hard to maintain.

<p style="color: red; font-size: 18px;">This is a red paragraph.</p>

[Link] Internal (Embedded) CSS


Internal CSS is written inside a <style> tag within the <head> section of an HTML document. It applies
to all matching elements within that single page, making it useful for page-specific styling without needing
an external file.

<head>
<style>
body { font-family: Arial, sans-serif; }
h1 { color: darkblue; text-align: center; }
</style>
</head>

[Link] External CSS


External CSS is written in a separate .css file and linked to one or more HTML documents using the <link>
tag inside the <head>. This is the most efficient and widely recommended method, because a single
stylesheet can control the styling of an entire website, making updates easy and consistent.

<!--Inside HTML <head> -->


<link rel="stylesheet"
href="[Link]">

/* Inside [Link] */
body {
background-color: #f5f5f5;
margin: 0;
}

Type Where Scope Best Use Case


Defined
Inline Inside Single Quick, one-off style overrides.
the element only.
element's
style
attribute.
Internal Inside The current Page-specific styling, small sites.
<style> page only.
in the
<head>.
External In a Any page that Large or multi-page websites.
separate links to the
.css file, file.
linked.
3.7.3 Styling Elements (Text, Colours, Backgrounds, Tables, Homepage Decoration)
CSS provides a wide range of properties to control appearance. Some of the most commonly used
categories are:

Category Common Properties Example


Text color, font-size, font-family, p { font-size: 16px; text-align:
font-weight, text-align justify; }
Colour & color, background-color, body { background-color: #eef2f7; }
Background background-image
Box Model margin, padding, border, width, div { padding: 10px; border: 1px
height solid #ccc; }
Layout display, position, float, flex, grid .container { display: flex; }

Example — decorating a simple homepage:

body {
font-family: 'Segoe UI', sans-serif;
background-color: #f0f4f8;
margin: 0;
}

.hero {
background-color: #1f3864;
color: white;
text-align: center;
padding: 60px 20px;
}

3.7.4 Decorating Tables and Other Elements with CSS


CSS can transform a plain, unstyled HTML table into a clear and visually appealing one by controlling
borders, spacing, alternating row colours, and header styling.

table {
width: 100%;
border-collapse: collapse;
}

th {
background-color: #1f3864;
color: white;
padding: 8px;
}

td {
padding: 8px;
border-bottom: 1px solid #ddd;
}

tr:nth-child(even) {
background-color: #f2f2f2;
}

Note: The border-collapse: collapse; property merges adjacent table and cell borders into a single
line, giving a cleaner, more professional appearance.

3.8 JavaScript

3.8.1 Introduction to JavaScript


JavaScript (JS) is a lightweight, interpreted programming language used to make web pages interactive
and dynamic. While HTML provides structure and CSS provides styling, JavaScript adds behaviour — it
can respond to user actions, validate form input, update content without reloading the page, and
communicate with servers in the background.

JavaScript is primarily a client-side scripting language, meaning it runs directly in the user's web browser,
though it can also run on servers using environments such as [Link]. It is included in an HTML page
using the <script> tag.

<script>
[Link]("Hello from JavaScript!");
[Link]("This is dynamic content.");
</script>

3.8.2 Variables and Data Types


A variable is a named container used to store data values that can be used and changed throughout a
program. In modern JavaScript, variables are declared using let (for values that can change), const (for
values that stay constant), or var (the older, less-preferred method).

JavaScript has several basic data types:

Data Type Description Example


String Textual data, written in quotes. let name = "Ali";
Number Integer or decimal numeric values. let age = 21;
Boolean A logical value: true or false. let isPassed = true;
Array An ordered list of values. let colors = ["red", "green"];
Data Type Description Example
Object A collection of key-value pairs. let student = {name: "Ali", age: 21};
Undefined/Null A variable with no assigned value / let x; // undefined
an intentional empty value.

let studentName = "Ayesha"; // String


let studentAge = 20; // Number
let isEnrolled = true; // Boolean
const schoolName = "City College"; // Constant, cannot be reassigned

3.8.3 Operators
Operators are symbols used to perform operations on variables and values.

Operator Type Examples Purpose


Arithmetic + - * / % ** Perform mathematical calculations.
Comparison == === != !== > < >= Compare two values, returning true or false.
<=
Logical && (AND) || (OR) ! Combine or invert boolean conditions.
(NOT)
Assignment = += -= *= /= Assign or update the value of a variable.

let a = 10, b = 3;

[Link](a + b); // 13 (Arithmetic)


[Link](a > b); // true (Comparison)
[Link](a > 5 && b < 5); // true (Logical AND)

Note: Use === (strict equality) instead of == in JavaScript wherever possible, since === compares
both value and data type, avoiding unexpected type-conversion bugs.

3.8.4 Conditional Statements


Conditional statements allow a program to make decisions and execute different blocks of code depending
on whether a condition is true or false. The most common form is the if-else statement, along with else if
for multiple conditions and switch for multiple fixed cases.

let marks = 78;

if (marks >= 90) {


[Link]("Grade: A+");
} else if (marks >= 70) {
[Link]("Grade: A");
} else if (marks >= 50) {
[Link]("Grade: B");
} else {
[Link]("Grade: Fail");
}
// Output: Grade: A

3.8.5 Iterative Statements (Loops)


Loops are used to execute a block of code repeatedly, either a fixed number of times or until a certain
condition becomes false. The main loop types in JavaScript are for, while, and do-while. A nested loop is
simply a loop placed inside another loop, often used for working with grids, tables, or multi-dimensional
data.

// A simple 'for' loop


for (let i = 1; i <= 5; i++) {
[Link]("Count: " + i);
}

// A 'while' loop
let n = 1;
while (n <= 3) {
[Link]("n = " + n);
n++;
}

// A nested loop - prints a 3x3 grid of coordinates


for (let row = 1; row <= 3; row++) {
for (let col = 1; col <= 3; col++) {
[Link](`Row ${row}, Col ${col}`);
}
}

3.8.6 Arrays
An array is a special variable used to store multiple values in a single, ordered structure. Each value
(element) in an array can be accessed using a numeric index, starting from 0.

let fruits = ["Apple", "Banana", "Mango"];

[Link](fruits[0]); // "Apple"
[Link]([Link]); // 3

[Link]("Orange"); // adds a new element to the end

for (let i = 0; i < [Link]; i++) {


[Link](fruits[i]);
}

3.8.7 Functions
A function is a reusable block of code designed to perform a specific task. Functions help avoid repeating
code, make programs easier to organize, and can accept inputs (parameters) and return an output (a value).

// Defining a function
function calculateArea(length, width) {
return length * width;
}

// Using (calling) the function


let area = calculateArea(5, 3);
[Link]("Area: " + area); // Area: 15

// A modern 'arrow function' equivalent


const greet = (name) => {
return "Hello, " + name + "!";
};
[Link](greet("Sara")); // Hello, Sara!

3.8.8 Event Handling and Making Pages Dynamic


An event is an action that occurs in the browser, such as a mouse click, key press, form submission, or the
page finishing loading. Event handling refers to writing JavaScript code that detects when such an event
occurs and runs a specific function in response, which is the core mechanism behind interactive, dynamic
web pages.

<button id="myButton">Click Me</button>


<p id="message"></p>

<script>
[Link]("myButton").addEventListener("click", function () {
[Link]("message").textContent = "Button was clicked!";
});
</script>

In this example, JavaScript selects the button element from the DOM, "listens" for a click event, and when
the event fires, it updates the text content of a paragraph — changing the page dynamically without a full
reload.

3.9 Debugging Code


3.9.1 Techniques for Identifying and Fixing Errors in JavaScript/HTML Code
Debugging is the systematic process of finding and fixing errors ("bugs") in code. Errors can generally be
grouped into three categories: syntax errors (incorrect code structure, e.g., a missing bracket), runtime
errors (the code runs but crashes during execution, e.g., calling a function that does not exist), and logical
errors (the code runs without crashing but produces the wrong result).

Technique Description
Browser Developer Opens the Console, Elements, and Sources panels to inspect
Tools (F12) HTML/CSS, view error messages, and step through JavaScript code.
[Link]() Prints variable values or messages to the browser console at chosen
points, helping track the program's flow and data state.
Breakpoints Pause code execution at a specific line in the Sources panel to inspect
variable values and step through code line-by-line.
Reading error messages Error messages usually state the error type and the exact line number,
which is the fastest way to locate a problem.
HTML validation Using a validator (e.g., the W3C Markup Validator) to catch
unclosed tags or invalid nesting.
Code isolation Commenting out sections of code to narrow down exactly which part
is causing the error.

Example — using [Link]() to debug a function:

function divide(a, b) {
[Link]("a =", a, " b =", b); // check the inputs
let result = a / b;
[Link]("result =", result); // check the output
return result;
}

divide(10, 0); // Logs: result = Infinity -> reveals a logical issue (division by zero)

Note: Good debugging habit: reproduce the error consistently, isolate the smallest piece of code that
causes it, check the browser console first, and fix one issue at a time before testing again.

You might also like