Docsity

Web Development Basics: HTML, CSS and JavaScript with a Working Project, Study Guides, Projects, Research of Web Design and Development

Toggle sidebar
bg1
Web Development Basics: HTML, CSS
and JavaScript with Working Examples
A study guide with a complete working project, a summary table and practice questions
Author: Psychedelic Tunes
How to use this guide. The guide builds one small but complete web page, a Study Planner, step by
step: HTML for structure, CSS for presentation and JavaScript for behaviour. The HTML passes an
automated validator, the JavaScript was run and tested, and the screenshot in Section 5 shows the
finished page in a real browser. To try it, save the three files index.html , styles.css and app.js in
one folder and open index.html in any browser.
Contents
How the web works
HTML: structure and meaning
CSS: presentation and layout
JavaScript: the language
JavaScript in the browser: the DOM and events
Summary table
Practice questions and answers
1. How the web works
When you type a URL such as https://example.com/about , the browser asks DNS for the server's IP
address, opens a connection, and sends an HTTP request ( GET /about ). The server replies with an
HTTP response: a status code (200 OK, 301 moved, 404 not found, 500 server error), headers, and a
body, usually HTML. The browser then requests the CSS, JavaScript and images that the HTML refers to,
and draws (renders) the page. HTTPS is HTTP encrypted with TLS.
Layer Language Job Analogy
Structure HTML (HyperText Markup
Language)
What the content is: headings, paragraphs,
forms, links
The frame and walls
of a house
Presentation CSS (Cascading Style
Sheets)
How it looks: colours, fonts, spacing, layout Paint and furniture
Behaviour JavaScript What it does: reacting to clicks, updating
content, talking to servers
Electricity and
plumbing
Keeping the three in separate files (separation of concerns) makes each easier to read, reuse and
maintain. This guide covers front-end (client-side) development, which runs in the browser. Back-end
(server-side) code runs on the server, in languages such as JavaScript (Node.js), Python, PHP or Java.
2. HTML: structure and meaning
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Study Planner</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>Study Planner</h1>
1.
2.
3.
4.
5.
6.
7.
Psychedelic Tunes Page 1 of 11
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Web Development Basics: HTML, CSS and JavaScript with a Working Project and more Study Guides, Projects, Research Web Design and Development in PDF only on Docsity!

Web Development Basics: HTML, CSS

and JavaScript with Working Examples

A study guide with a complete working project, a summary table and practice questions

Author: Psychedelic Tunes

How to use this guide. The guide builds one small but complete web page, a Study Planner , step by step: HTML for structure, CSS for presentation and JavaScript for behaviour. The HTML passes an automated validator, the JavaScript was run and tested, and the screenshot in Section 5 shows the finished page in a real browser. To try it, save the three files index.html , styles.css and app.js in one folder and open index.html in any browser.

Contents

How the web works HTML: structure and meaning CSS: presentation and layout JavaScript: the language JavaScript in the browser: the DOM and events Summary table Practice questions and answers

1. How the web works

When you type a URL such as https://example.com/about , the browser asks DNS for the server's IP address, opens a connection, and sends an HTTP request ( GET /about ). The server replies with an HTTP response : a status code (200 OK, 301 moved, 404 not found, 500 server error), headers, and a body, usually HTML. The browser then requests the CSS, JavaScript and images that the HTML refers to, and draws (renders) the page. HTTPS is HTTP encrypted with TLS.

Layer Language Job Analogy Structure HTML (HyperText Markup Language)

What the content is: headings, paragraphs, forms, links

The frame and walls of a house Presentation CSS (Cascading Style Sheets)

How it looks: colours, fonts, spacing, layout Paint and furniture

Behaviour JavaScript What it does: reacting to clicks, updating content, talking to servers

Electricity and plumbing

Keeping the three in separate files ( separation of concerns ) makes each easier to read, reuse and maintain. This guide covers front-end (client-side) development, which runs in the browser. Back-end (server-side) code runs on the server, in languages such as JavaScript (Node.js), Python, PHP or Java.

2. HTML: structure and meaning

Study Planner

Study Planner

Plan your week, one task at a time.

Add a task

Task

Hours

Add task

This week

Total planned: 0 hours

Made with HTML, CSS and JavaScript

Anatomy of an element. Task has an opening tag , content and a closing tag. for="task" is an attribute (a name–value pair in the opening tag). Some elements are void and have no closing tag: , , , , .

Key parts of the page above

tells the browser to use modern standards mode. holds information about the page: the character set, the viewport setting (needed for mobile layouts), the shown in the browser tab, and the link to the stylesheet. <body> holds everything visible. Semantic elements ( <header> , <main> , <section> , <footer> , <nav> , <article> , <aside> ) describe the meaning of each part. They help screen readers, search engines and other developers, unlike a page built only from <div> s. Forms: each <input> has an id , and its <label for="..."> points to that id. Clicking the label focuses the input, and screen readers read the label aloud. type="number" , min , step and required give built-in validation. The <script> tag is placed at the end of the body so the HTML elements exist before the script looks for them. (Adding defer to a script in the head has the same effect.)

Element(s) Purpose <h1> … <h6> Headings, from most to least important; use one <h1> per page <p> Paragraph <a href="url"> Link ( target="_blank" opens a new tab) <img src="…" alt="…"> Image; alt text describes it for screen readers and when it fails to load <ul> , <ol> , <li> Unordered (bullets) and ordered (numbered) lists, and their items

cursor: pointer; }

button:hover { background: #1b3a5c; } /* pseudo-class: mouse over */

#task-list li { padding: 6px 0; border-bottom: 1px solid #eee; } #task-list li.done { text-decoration: line-through; color: #888; }

.error { color: #b00020; min-height: 1.2em; }

/* 3. Media query: stack the cards on narrow screens */ @media (max-width: 600px) { main { flex-direction: column; } }

A CSS rule has a selector (which elements) and a declaration block of property: value; pairs. Example: label { display: block; font-weight: bold; }.

Selector Matches Example in the stylesheet p Every element of that type body , label .name Elements with class="name" .card , .error #name The one element with id="name" #task-list A B B anywhere inside A (descendant)^ #task-list li A, B Both A and B^ header, footer A.b A elements that also have class b^ li.done :hover , :focus Elements in a state (pseudo-class) button:hover

  • Every element * { box-sizing: border-box; }

The cascade and specificity. When several rules set the same property on the same element, the browser picks the winner by: (1) importance ( !important beats normal declarations; avoid it), (2) specificity , then (3) source order , where the later rule wins. Specificity is counted as (ids, classes / attributes / pseudo-classes, elements): #task-list li = (1, 0, 1) beats li.done = (0, 1, 1), which beats li = (0, 0, 1). Inline style="..." attributes beat all selectors.

The box model. Every element is a box made of content , padding (space inside the border), border and margin (space outside the border). By default ( box-sizing: content-box ) the width property sets only the content width, so a box with width: 200px; padding: 20px; border: 5px solid is 200 + 2 × 20 + 2 × 5 = 250 px wide on screen. With box-sizing: border-box , as in the stylesheet, width includes padding and border, so the box is exactly 200 px. This is why many stylesheets start with * { box-sizing: border-box; }.

Layout with flexbox. display: flex on a container lays its children in a row. gap adds space between them; flex: 1 on each child shares the space equally; justify-content aligns along the main axis and align-items along the cross axis; flex-direction: column stacks them. CSS Grid ( display: grid ) is the companion tool for two-dimensional layouts of rows and columns.

Responsive design. The media query @media (max-width: 600px) applies its rules only on screens 600 px wide or less, where the cards stack vertically. Combined with the viewport tag and relative units, this makes one page work on phones and desktops. Useful units: px (fixed), % (of the parent), rem (relative to the root font size), em (relative to the element's font size), vw / vh (percent of the viewport).

Three ways to add CSS: an external stylesheet linked with (best: one file styles many pages), an internal week += 1; console.log(course, "week", week, typeof course, typeof week);

// Strict (===) vs loose (==) equality console.log(5 == "5", 5 === "5", null == undefined, null === undefined);

// Template literals const price = 19.5, qty = 3; console.log(Total: $${(price * qty).toFixed(2)});

// Functions: declaration and arrow function function greet(name = "student") { return Hello, ${name}!; } const square = (n) => n * n; console.log(greet(), greet("Ava"), square(7));

// Arrays and the big three methods const scores = [72, 95, 58, 88, 64]; const curved = scores.map((s) => s + 5); const passing = scores.filter((s) => s >= 65); const average = scores.reduce((sum, s) => sum + s, 0) / scores.length; console.log(curved, passing, average);

// Objects const student = { name: "Ben", gpa: 3.4, courses: ["HTML", "CSS"] }; student.courses.push("JS"); console.log(student.name, student["gpa"], student.courses.length, Object.keys(student));

// Control flow for (let i = 1; i <= 3; i++) { console.log(i % 2 === 0? ${i} is even : ${i} is odd); }

// Watch out: + joins strings console.log("2" + 3, "2" * 3, Number("2") + 3);

Output (run with Node.js)

Web Basics week 2 string number true false true false Total: $58. Hello, student! Hello, Ava! 49 [ 77, 100, 63, 93, 69 ] [ 72, 95, 88 ] 75. Ben 3.4 3 [ 'name', 'gpa', 'courses' ] 1 is odd 2 is even 3 is odd 23 6 5

What to notice

const for values that will not be reassigned, let for those that will. Both are block-scoped (they exist only inside the { } where they are declared). The older var is function-scoped and best avoided. Types: number (integers and decimals are the same type), string , boolean , undefined (declared but not assigned), null (deliberately empty), object (including arrays) and bigint / symbol. Check with typeof. Always use === (strict equality: same value and type). == converts types first, so 5 == "5" is true , a common source of bugs. + with a string joins , so "2" + 3 is "23" , but * converts to numbers, so "2" * 3 is 6. Convert input with Number() before adding.

How it works, step by step

Select elements with document.querySelector(cssSelector) , which accepts the same selectors as CSS. ( querySelectorAll returns all matches; getElementById("task") is an older equivalent for ids.) Keep the state (the list of tasks) in a JavaScript array, and write one render() function that redraws the list from that array. This keeps the page and the data in step. addEventListener("submit", handler) runs the handler when the form is submitted. event.preventDefault() stops the browser's default action, which would reload the page. Validate the input: .value from an input is always a string, so Number() converts the hours. If the name is empty or the hours are not positive, an error message is shown and the function return s early. document.createElement("li") , textContent and appendChild build new elements. Using textContent rather than innerHTML for user input prevents cross-site scripting (XSS) : if someone types , it is shown as text instead of being run. Clicking an item toggles its done property, and classList.add("done") applies the CSS rule li.done (strike-through). reduce adds up the hours for the total.

Automated test. The page was loaded in a simulated browser (jsdom), three tasks were added (2, 1. and 3 hours), one empty submission was attempted, and the first task was clicked. The results:

error: Enter a task name and a positive number of hours. [ 'Read chapter 3 (2 h) [done]', 'Practice CSS flexbox (1.5 h)', 'Build the planner page (3 h)' ] total: 6.5 | error now: ""

The empty task was rejected with the message, the error cleared on the next valid entry, the clicked task gained the done class, and the total is 2 + 1.5 + 3 = 6..

The finished page in a desktop browser:

Common events: click , submit , input (every change to a field), change (field loses focus after changing), keydown , mouseover , DOMContentLoaded (the HTML has finished loading).

Developer tools. Press F12 (or right-click → Inspect ) in any browser. The Elements panel shows the live DOM and the CSS rules applied to each element; the Console shows console.log output and errors; the Network panel shows every request and its status code.

Answers

1. HTML defines the structure and meaning of content; CSS controls appearance and layout; JavaScript adds behaviour and interactivity. 2. 200: OK, the request succeeded. 404: Not Found, the resource does not exist. 500: Internal Server Error, the server failed while handling the request. 3. The browser reads HTML from top to bottom. A script in the head would run before the elements it looks for exist, so querySelector would return null. Placing it at the end of the body (or using defer ) runs it after the HTML is parsed, and also lets the page appear sooner. 4. , , , , (any three). They describe the role of their content, which helps screen-reader users navigate, helps search engines understand the page, and makes the code easier to read. 5. Screen readers read the alt text to visually impaired users; it is shown if the image fails to load; and search engines use it. Purely decorative images should have an empty alt="" so screen readers skip them. 6. Block elements start on a new line and take the full available width: ,

,

, . Inline elements flow within text and are only as wide as their content: , , , . 7. Visit ( rel="noopener" stops the new page from controlling the original one). 8. A class ( .card ) can be used on many elements and an element can have several classes; an id ( #total ) must be unique on the page. Use classes for styling groups of elements, and ids for one unique element, such as one that JavaScript needs to find. 9. Highest to lowest: #task-list li (1, 0, 1), then li.done (0, 1, 1), then li (0, 0, 1). 10. content-box: 200 + 2 × 20 + 2 × 5 = 250 px. border-box: 200 px (the content shrinks to 200 − 40 − 10 = 150 px).

11.

.container { display: flex; gap: 10px; } .card { flex: 1; }

(where .container is the parent of the three cards).

12.

@media (max-width: 479px) { nav { font-size: 14px; } }

( max-width: 480px is also commonly accepted; strictly "narrower than 480" means up to 479 px.)

13. const cannot be reassigned and let can; both are block-scoped. var is function-scoped, can be redeclared, and is "hoisted" in ways that cause bugs, so modern code avoids it. 14. "10" - 2 is 8 : - only works on numbers, so the string is converted. "10" + 2 is "102" : + with a string performs concatenation. 15. true false. Loose equality converts "5" to a number; strict equality also compares types (number vs string). 16. [20, 40]. filter keeps 2 and 4, and map multiplies each by 10. 17. By default, sort() compares items as strings , and "10" comes before "5" alphabetically. Pass a compare function: [10, 1, 5].sort((a, b) => a - b) gives [1, 5, 10].

18.

function countVowels(str) { return [...str.toLowerCase()].filter((c) => "aeiou".includes(c)).length;

console.log(countVowels("JavaScript Basics")); // 5

19. A form's default action is to send the data and reload the page, which would wipe the tasks stored in the JavaScript array. preventDefault() stops that so the script can handle the data itself. 20. innerHTML would treat whatever the user typed as HTML, so a malicious entry could inject a script (cross-site scripting). textContent always inserts plain text, so the input is displayed exactly as typed and never executed.

This guide is an original study aid written for revision. The example HTML was checked with an HTML validator, the JavaScript was run with Node.js and tested in a simulated browser, and the screenshot was taken in a headless browser.