0% found this document useful (0 votes)
16 views192 pages

Full Stack Web Development

Uploaded by

adityawalt16
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)
16 views192 pages

Full Stack Web Development

Uploaded by

adityawalt16
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
You are on page 1/ 192

Untitled

Saturday, May 3, 2025 9:47 PM

What is the Internet?


Hey! Let's learn how the Internet works

Internet = Giant Spiderweb of Wires

There are 2 kinds of computers on the Internet:


• Client (that's YOU!): You ask for websites
• Server : Gives you the websites
Think of a server like a big library. You ask for a book (a website), and the server gives it to you .

How Your Computer Finds a Website


When you type google.com, your computer doesn’t know where it is! It needs help finding it
So it follows these steps:

You →Y P → DNS S →G
And then, Google sends back the webpage to you! ✨

What is an IP Address?
Every computer has a special number called an IP Address . It's like a home address so other
computers can find it.

Under the Ocean?


Yup! The Internet goes through big fat wires under the ocean . These are called submarine
cables and they shoot lasers to send data super fast!

Frontend Web Development Page 1


Summary
• Internet = Lots of wires
• You = Client
• Server = Shares websites
• DNS = Finds the website's number
• IP Address = Computer’s home
• Cables under oceans = Zooming lasers!

Frontend Web Development Page 2


Untitled
Saturday, May 3, 2025 9:53 PM

How Websites Work — Code Edition


Think of building a website like building a toy house with LEGO blocks.
Step 1: HTML – The Bricks
HTML is the stuff you see like the text, buttons, and pictures.

<!-- This is the base -->


<h1> Welcome to My Website!</h1>
<p>I love dogs and pizza .</p>
<button>Click Me!</button>
<img src="dog.png" alt="Cute Dog">

Step 2: CSS – The Paint & Style


CSS is what makes everything look pretty. Like colors, fonts, and layout.

/* This is the styling */


h1 {
color: purple;
font-size: 40px;
}
button {
background-color: gold;
border-radius: 12px;
font-weight: bold;
}


JavaScript makes your site do stuff like respond when you click something.

javascript

B ’
The browser puts it all together:
1. Reads HTML to build the stuff.
2. Reads CSS to make it pretty.
3. Reads JavaScript to add action.

Frontend Web Development Page 3


Right-click → y see and change the LEGO pieces of real websites just for fun

html

<!-- Imagine you change this in Inspect -->


<button value="Google Search">Angela Search</button>

You can pretend you're hacking the site (but really, it's just your screen hit refresh and it goes
away!).

Summary:
Part Job Emoji
HTML Structure / Content
CSS Colors / Looks
JavaScript Movement / Actions
Browser The builder and presenter

Frontend Web Development Page 4


Untitled
Saturday, May 3, 2025 9:55 PM

Main Idea:
Getting stuck in programming is inevitable but also essential to learning. The real growth comes from
solving those challenges.

Core Steps to Get Unstuck in Programming:


1. Expectation vs. Reality:
○ Ask yourself: What did I expect to happen? What actually happened?
○ Helps pinpoint where your logic or syntax diverged.
2. Read & Search Error Messages:
○ D ’ b f y’
○ Copy and paste them into Google.
○ Prioritize Stack Overflow results ’ ’ -to site.
3. Re-watch Tutorial Videos:
○ Go back a minute or two before the problem occurred.
○ Look for:
▪ Typos
▪ Capitalization errors
▪ Missed steps
4. Compare with Completed Code:
○ Use the final project files provided.
○ Scroll and compare line by line.
○ Paste parts into your own code to isolate the issue.
5. Use the Q&A Section:
○ Look through existing questions on the same lecture.
○ Ask your question t t l t ’ Q&A.
○ Include:
▪ What you expected vs. what happened
▪ Code screenshot
▪ Error messages/debug console screenshot
▪ Video timestamp (if relevant)

• Windows: Win + Shift + S


• Mac: Cmd + Shift + 4

Use these to capture only relevant parts of your screen useful for Q&A and debugging.

Mindset Advice:
• Everyone gets stuck even Angela does.
• Debugging is frustrating but deeply rewarding.
• Embrace bugs as learning opportunities even a missing comma can take hours but teaches
precision.

✅ Helpful Reminders:
• Getting stuck = part of becoming a great developer.
• Learn the process of debugging, not just the syntax.
• Build resilience it pays off when things click.

Frontend Web Development Page 5


Untitled
Saturday, May 3, 2025 10:00 PM

What is HTML and How Do We Use It to Create Websites?


What does HTML do?
• HTML stands for HyperText Markup Language.
• It defines the content and structure of a website.
• Browsers (like Chrome or Safari) use HTML + CSS + JavaScript to render websites.
• You can have a full webpage with just HTML no CSS or JavaScript needed to start.

Understanding "HyperText"
• Hypertext = Text with links (hyperlinks) to other documents or pages.
• These are the blue links we click on clicking takes us to another page (another HTML file).
• It's the foundation of navigation in web pages.
x : "P j " k “H w ?” → H ML f

• Markup = Symbols or tags used to define parts of text.


• Similar to how editors mark:
○ Quotes → w q k
○ Bold → w q
○ Underline → w
HTML uses tags like <h1>, <p> to do this digitally.

• HTML uses tags to mark parts of a page:


○ <h1> to <h6>: Headings
○ <p>: Paragraphs
○ <a>: Links (hyperlinks)
• These tags help browsers understand how to display content.

Don't Worry About Memorizing Everything


• Y ’ y
• Focus on using the common ones in projects:
○ Headings (<h1> to <h6>)
○ Paragraphs (<p>)
○ Links (<a>)

✅ Key Takeaways
Concept Meaning/Use
HTML The backbone structure/content of any website
HyperText Text that links to other documents/pages (via hyperlinks)
Markup System to annotate content (like tags)
HTML Tags Used to mark content: headings, paragraphs, links, etc.
First Website Made using only HTML by Sir Tim Berners-Lee

Introduction to HTML Page 6


First Website Made using only HTML by Sir Tim Berners-Lee
Beginner Focus Learn common tags; don’t memorize everything at once

Introduction to HTML Page 7


Untitled
Saturday, May 3, 2025 10:02 PM

Simple Notes: HTML Headings


What is an HTML Heading Element?
• A heading element helps structure a webpage, just like headings in a book.
• It shows different levels of importance: h1 is the most important, h6 is the least.

Tags vs Elements
Term Meaning
Tag Code inside angle brackets (e.g., <h1> or </h1>)
Element The whole block: opening tag + content + closing tag (e.g., <h1>Hello</h1>)

Example:
html

<h1>Hello World</h1>

• <h1> = opening tag


• </h1> = closing tag
• Hello World = content
• The whole thing is the heading element

Heading Levels:
Heading Use Case Size (Default)
<h1> Main title (Book title) Largest
<h2> Chapter title Smaller
<h3> Section title Smaller
<h4> Subsection title Smaller
<h5> Tiny headings Tiny
<h6> Smallest Smallest

Do's and Don'ts:

• ✅ Use one <h1> per page (represents the main idea).


• ✅ Use headings in order: h1 → 2 → 3
• ❌ Don't skip levels (e.g., from h1 to h4).
• ❌ Don't use h7 ’ x !

Introduction to HTML Page 8


Introduction to HTML Page 9
Untitled
Saturday, May 3, 2025 10:22 PM

Paragraphs in HTML (10-Year-Old Mode)


Big Idea:
When you type text in HTML, it’s like writing in a notebook , but without spaces to show where each
part starts and ends. To fix this, we use paragraphs to separate the text and make it neat.

A paragraph is like a box that holds a piece of text. In HTML, we use the <p> tag to start a paragraph
and </p> to end it.

Without paragraphs, everything looks jumbled together.


With paragraphs, each section of text is neatly separated and easy to read! ✅

Why is this important?


• For you: It helps organize your website text .
• For blind users: Screen readers use paragraphs to tell where one part ends and the next begins.

How It Works:
Let's say we want to make 3 paragraphs:
• We use <p> to start each paragraph.
• We use </p> to end each one.

Code Example:
Here’s the code to separate 3 paragraphs:

html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Paragraph Example</title>
</head>
<body>
<p>This is the first paragraph. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>This is the second paragraph. Donec vel mauris quam. Nullam ac eros at ligula
tincidunt.</p>
<p>This is the third paragraph. Etiam vestibulum, turpis ac rhoncus varius, mi dui posuere
nisi.</p>
</body>
</html>

Introduction to HTML Page 10


</html>

Key Point:
Using the <p> tag is important for separating paragraphs and making your text readable!

Fun Add-On Challenge:


• Try using Lorem Ipsum for practice!
• Want a silly version? Try Bacon Ipsum (with bacon words ) or Bro Ipsum (with bro words ).
You can find these tools online to generate fun placeholder text.

Introduction to HTML Page 11


Untitled
Saturday, May 3, 2025 10:07 PM

Void Elements in HTML


What Are Void Elements?
• Void elements are tags in HTML that don't have any content inside them.
• Unlike regular tags (like <p> for paragraphs or <h1> for headings), void elements only need an
opening tag and don’t have a closing tag.

Void Element Examples


1. Horizontal Rule (<hr />)
○ Creates a line to separate sections on your webpage.
Code:

html

<hr />

2. Break (<br />)


○ Forces a line break within the text.
Example: for poems or addresses where lines need to be split.
Code:

html

<br />

L t’ T y It t C d !
Here’s how we can use these elements:

html

<!DOCTYPE html>
<html>
<head>
<title>Poem by William Blake</title>
</head>
<body>
<h1>William Blake</h1>

<!-- Address with break elements -->


<p>4 Fountain Court,<br />
Broad Street,<br />
London.</p>
<!-- Horizontal Rule -->
<hr />
<!-- Poem with breaks to separate lines -->
<p>To see a World in a Grain of Sand<br />

Introduction to HTML Page 12


<p>To see a World in a Grain of Sand<br />
And Heaven in a Wild Flower,<br />
Hold Infinity in the palm of your hand<br />
And Eternity in an hour.</p>
</body>
</html>

Here's the Explanation:


1. <br /> in the address makes sure each line appears on a new line (because addresses are usually
separated by new lines).
2. <hr /> creates a horizontal line to separate the address and the poem, making it visually clearer.
3. The poem is split using <br /> to keep the lines correct as it should be read.

Quick Reminder for Void Elements:


• They d ’t av l ta .
• You just write the tag like <hr /> or <br />.

Introduction to HTML Page 13


Untitled
Saturday, May 3, 2025 10:25 PM

What Did We Learn? (HTML Lists)


Imagine you're baking cinnamon rolls and writing a recipe for your friend.
You need to show:
1. Ingredients – ’ w f
2. Instructions – must follow in the right order
’ x yw lists do in HTML!

TL;DR – Easy Peasy!


List Type HTML Tag What You See When To Use
Unordered List <ul> •B P Order doesn't matter
Ordered List <ol> 1. 2. 3. Steps must be followed

Example: Cinnamon Roll Recipe


• Ingredients: use <ul>
• Instructions: use <ol>
This keeps your website easy to read and clear for everyone!

Intermediate HTML Page 14


Untitled
Saturday, May 3, 2025 10:44 PM

1. The Visual Learner


"Show me what it looks like!"
Let's go with a diagram (text-based, simple indentation):

css

<ul>
<li>A</li>
<li>B
<ol>
<li>B1</li>
<li>B2
<ul>
<li>B2a
<ul>
<li>B2aa</li>
<li>B2ab</li>
</ul>
</li>
<li>B2b</li>
<li>B2c</li>
</ul>
</li>
<li>B3
<ol>
<li>B31</li>
<li>B32</li>
</ol>
</li>
</ol>
</li>
<li>C</li>
</ul>

Tip: Every new list is nested inside a <li> like layers in a sandwich .

2. The Coder
"Give me clean HTML to copy and learn."

html

<ul>
<li>A</li>
<li>B

Intermediate HTML Page 15


<li>B
<ol>
<li>B1</li>
<li>B2
<ul>
<li>B2a
<ul>
<li>B2aa</li>
<li>B2ab</li>
</ul>
</li>
<li>B2b</li>
<li>B2c</li>
</ul>
</li>
<li>B3
<ol>
<li>B31</li>
<li>B32</li>
</ol>
</li>
</ol>
</li>
<li>C</li>
</ul>

Look at how each </li> comes after the nested list!

3. The Young Learner


"Tell me like I’m five."
A box of fruits:
• A
• B
1. B1
2. B2
▪ B2a
□ B2aa
□ B2ab
▪ B2b
▪ B2c
3. B3
1. B31
2. B32
• C

4. The Chill Learner


"Give me a vibe, not a lecture."
This is like a tree :
• Main branches (A, B, C)
• B has sub-branches (B1, B2, B3)

Intermediate HTML Page 16


• B has sub-branches (B1, B2, B3)
• B2 branches again into B2a → : B2 , B2 b

5. The Detective Learner


"What's the trick?"
Trick = You can only nest a new list inside a <li>. Not before or after.
Common Mistake:

html

<ul>

<ul>❌ wrong
Fix:

html

<ul>
<li>

<ul>✅ correct

"What’s the law here?"


• ✅ You can put a <ul> or <ol> inside a <li>.
• ❌D ’ < >b f close it after.
Example:

html

<li>B2
<ul> ... </ul>
</li>

7. The Logical Learner


"I want the hierarchy."
Think of it like this structure:

css

UL
LI A
LI B
OL
LI B1
LI B2
UL
LI B2a
UL

Intermediate HTML Page 17


UL
LI B2aa
LI B2ab
LI B2b
LI B2c
LI B3
OL
LI B31
LI B32
LI C

8. The Tester
"I’ll try and break it."
Challenge: What happens if you don’t close a <ul>?
Spooky HTML:

html

<li>B
<ul>
<li>B1
</ul>
<li>C</li>

❌ Browser may still render it, but code is broken inside!


✅ Always match opening and closing tags.

9. The Designer
"Can I make it pretty?"
Nesting also changes how lists look on the page:
• ul uses bullets
• ol uses numbers
• Deeper nests →
So the final structure looks like this:

markdown

•A
•B
1. B1
2. B2
• B2
• B2
• B2 b
• B2b
• B2
3. B3
1. B31
2. B32

Intermediate HTML Page 18


2. B32
•C

10. The Teacher Learner


"How do I explain this to others?"
Use this mnemonic:
"Every List Item Is a Portal to Another List"
Teach that:
• Lists can nest inside <li>
• Tags must wrap properly
• Indentation matters (but VS Code helps!)
• Visual structure = mental clarity

Intermediate HTML Page 19


Untitled
Saturday, May 3, 2025 10:45 PM

HTML Anchor Tags & Attributes – Notes


Anchor Tag (<a>)
• Used to create hyperlinks.
• Syntax:

html

<a href="https://example.com">Visit Example</a>

○ <a> = anchor element


○ href = attribute that holds the link destination
○ Text between the tags = clickable link
Attributes in HTML
• Provide extra information about elements.
• Always go inside the opening tag.
• General format:

html

<tag attribute="value">Content</tag>

href Attribute
• Specific to the <a> tag.
• Without it, the anchor tag is not clickable.
• Example:

html

<a href="https://google.com">Google</a>

Global Attributes
• Can be used on any HTML element.
• Example:

html

<a href="https://example.com" draggable="true">Drag me</a>

✅ Goal
Create an ordered list (<ol>) of 5 favorite websites, each as a clickable hyperlink.
✅ Code:

html

<h1>My Top 5 Favorite Websites</h1>

Intermediate HTML Page 20


<h1>My Top 5 Favorite Websites</h1>
<ol>
<li><a href="https://producthunt.com">Product Hunt</a></li>
<li><a href="https://github.com">GitHub</a></li>
<li><a href="https://unsplash.com">Unsplash</a></li>
<li><a href="https://stackoverflow.com">Stack Overflow</a></li>
<li><a href="https://medium.com">Medium</a></li>
</ol>

Bonus: Start Ordered List from 5


Use the start attribute in the <ol> tag:

html

<ol start="5">
<li><a href="https://example1.com">Site 1</a></li>
<li><a href="https://example2.com">Site 2</a></li>
<li><a href="https://example3.com">Site 3</a></li>
<li><a href="https://example4.com">Site 4</a></li>
<li><a href="https://example5.com">Site 5</a></li>
</ol>

Intermediate HTML Page 21


Untitled
Saturday, May 3, 2025 10:47 PM

HTML Image Tag (<img>) – Notes


Basic Syntax

html

<img src="url" />

• img = image element.


• src = source of the image (URL or file path).
• Self-closing tag (no closing </img>).
• It's a void element, just like <br> and <hr>.
Example with a Placeholder Image

html

<img src="https://picsum.photos/200" />

• Displays a random image, 200x200 pixels.


• picsum.photos = great for placeholder images (like "Lorem Ipsum" for text).
alt Attribute
• Describes the image for screen readers (accessibility).
• Helps visually impaired users understand the content.
• Example:

html

<img src="https://picsum.photos/200" alt="Forest during sunset" />

Accessibility Tip
• Always use alt text unless the image is purely decorative.
• Screen readers will read the alt text aloud.

✅ Goal
Create a heading and add an image of a dog or cat with a proper alt tag.
✅ Code (Dog Example):

html

<h1>I'm a dog person</h1>


<img src="https://raw.githubusercontent.com/appbrewery/webdev/main/dog-img.jpg"
alt="Puppy digging in the sand" />

✅ Code (Cat Example):

Intermediate HTML Page 22


html

<h1>I'm a cat person</h1>


<img src="https://raw.githubusercontent.com/appbrewery/webdev/main/cat-img.jpg"
alt="Chill cat lying down" />

• Dog image is a GIF (animated).


• Cat image is a JPG (static).

Intermediate HTML Page 23


Untitled
Saturday, May 3, 2025 10:50 PM

What is a File Path?


• A file path tells the computer where a file or folder is located.
• Just like giving directions to a specific location, a path guides the computer to a file.

Two Main Types of File Paths


✅ 1. Absolute Path
• Starts from the root of the file system.
• Always points to the same location.
• Examples:
○ Windows: C:\Users\John\Documents\Project\Images\cat.png
○ Mac: /Users/john/Documents/Project/Images/cat.png
✅ 2. Relative Path
• Starts from the current file location.
• Depends on where the referencing file is.
• Shorter, more flexible for web development.
• Example (from index.html in the same folder as dog.png):
./dog.png

Special Characters in Relative Paths


Character Meaning Example
. Current folder ./image.png
.. Go up one folder ../essay.docx
./ Explicitly current directory (recommended) ./rabbit.png
(nothing) Also refers to current folder (not always reliable) dog.png

Why Use Relative Paths in Web Development?


• Works even if you move the entire project folder.
• More portable and consistent across environments.
• Often used in:

html

<img src="./images/dog.png" alt="Dog">

✅ Best Practices
1. Always add alt text for accessibility.
2. Use ./ when accessing files in the same folder.
3. Use ../ when going up a folder level.
4. Use VS Code's auto-suggestions to prevent errors.
5. If the image doesn't load → k y

Code Examples
Multi-Page website Page 24
Code Examples
✅ Access file in the same folder

html

<img src="./rabbit.png" alt="Rabbit">

✅ Access file inside a subfolder

html

<img src="./images/fish.png" alt="Fish">

✅ Go up one level and access a file

html

<img src="../bird.png" alt="Bird">

✅ Go up and into another folder

html

<img src="../Folder3/cat.png" alt="Cat">

Multi-Page website Page 25


Untitled
Saturday, May 3, 2025 10:55 PM

✅ Multi-Page Website Folder Structure


pgsql

project-folder/
index.html ←
about.html ← b
public/
contact.html ←
assets/
images/
cat.png

✅ Creating Navigation Between Pages (Using File Paths)


Linking to another HTML page (from index.html)

html

<a href="./about.html">About Me</a>


<a href="./public/contact.html">Contact Me</a>

html

<a href="./public/about.html">
<img src="./assets/images/cat.png" alt="Cat image">
</a>

✅ File Path Review for cat.png


If index.html is in the root, and image is in:

bash

assets/images/cat.png
Correct path in <img>:

html

<img src="./assets/images/cat.png" alt="A cute cat">

✅ Common Mistakes
• ❌ Using href in <img> →
❌ Using a tag to show images → f b k b k

Multi-Page website Page 26


• ❌ Using a tag to show images → f b k b k
• ❌ Using .. when not going up a folder.

✅ Challenge Summary
1. Add a link to Contact Me page:

html

<a href="./public/contact.html">Contact Me</a>

2. Add a clickable image that links to the About page:

html

<a href="./public/about.html">
<img src="./assets/images/cat.png" alt="About Me">
</a>

Multi-Page website Page 27


Untitled
Saturday, May 3, 2025 10:57 PM

✅ HTML Boilerplate: The Structure of Every HTML Page


What is a Boilerplate?
• It’s like the template or basic skeleton of every HTML page.
• Just like a letter has a structure (address, greeting, body, sign-off), an HTML file has:

○ <!DOCTYPE html>
○ <html>
▪ <head>
▪ <body>
○ </html>

HTML as a Hamburger (Analogy)


• Top Bun: <html> (opening)
• Lettuce (Head): <head> – invisible info for the browser (not the user)
• Tomatoes, Patty, etc. (Body): <body> – visible content (images, text, etc.)
• Bottom Bun: </html> (closing)

Key Elements in Boilerplate


1. <!DOCTYPE html>
• Declares the version of HTML (HTML5 in this case)
• Tells browser how to render the file
2. <html lang="en">
• Root element; wraps the whole HTML content
• lang="en" helps screen readers pronounce text correctly
3. <head>
• Metadata goes here (not shown to the user)
• Includes:
○ <meta charset="UTF-8">: character encoding (supports emojis and symbols)
○ <title>My Website</title>: text that appears in the browser tab
○ (Optional) <meta name="viewport"...>: responsive design on mobile
4. <body>
• All visible content of your webpage goes here:
○ Headings (<h1>)
○ Paragraphs (<p>)
○ Images (<img>)
○ Links (<a>)
○ Lists, etc.

Tips for Writing HTML


• Nesting: Tags go inside other tags like a burger layer!
• Indentation: Use spaces (2 or 4) to show nesting visually
• Shortcuts in VS Code:
○ Type ! + Enter in a .html file → b
• Clean code: You can remove old IE-specific meta tags

Multi-Page website Page 28


Github
Saturday, May 3, 2025 11:00 PM

This lesson covers the process of web hosting and how to make your website live on the internet. Here's
a summary:
1. Web Hosting Definition: It's the process of making your website available on the internet. This is
done by uploading your website files (like HTML, CSS, images) to a web server that is always
connected to the internet.
2. Local vs. Web Hosting:
○ Locally, the website files are stored on your computer, and you can only view the website on
your device.
○ With web hosting, you upload these files to a server, making the website accessible to
anyone, anywhere in the world.
3. Using GitHub for Hosting:
○ Create a repository on GitHub (public and with a README file).
○ Upload all your website files (including index.html, images, and other folders) to the
repository.
○ Ensure the index.html file is correctly named and includes your homepage code.
○ In GitHub settings, enable GitHub Pages by selecting the main branch to serve your website.
○ After a few minutes, you'll get a URL where your website is live.
4. Access and Share: Once the website is live, you can share the URL with anyone, allowing them to
view your portfolio or website.
This is a simple process that makes your website accessible globally. Next, the course will cover styling
your website with CSS to improve its appearance.

Multi-Page website Page 29


Untitled
Saturday, May 3, 2025 11:16 PM

What is CSS?
Cascading = Waterfall
Imagine a waterfall .
• Water starts from the top (general) and falls down to the bottom (specific) .
• CSS works the same way! It starts with big rules (like “everything is blue”) and goes down to
smaller ones (like “only the title is red”).

What is a Style Sheet?


A Style Sheet is a list of rules that tells your website how to look!
For example:
• What colors should the text be?
• What font should be used?
• hould it be centered or on the le ?

A long time ago, websites were boring. They were only made with HTML, and everything looked the
same .
But then, we got CSS! This allowed us to:
• Separate content (HTML) from style (CSS).
• Now websites could look awesome!

CSS Changes Everything!


CSS gives websites life by adding cool styles, like colors, fonts, and layouts. Without it, a website would
look plain like a blank sheet of paper .

Let's See It in Action!


Here s a a C a l that changes the background color of a webpage and makes the text bold.

html

<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: lightblue; /* Page color */
}
h1 {
font-family: 'Arial'; /* Font for headings */
color: red; /* Text color */
}
</style>

Introduction to CSS Page 30


</style>
</head>
<body>
<h1>Hello, CSS World!</h1>
<p>Welcome to my styled webpage!</p>
</body>
</html>

1. The background will turn light blue .


2. The heading text will be red and bold.

What Did We Learn?


• CSS = Making websites beautiful .
• Cascading = Like a waterfall, starting general and getting more specific ⛲.

Introduction to CSS Page 31


Untitled
Saturday, May 3, 2025 11:24 PM

CSS in HTML (Using Three Methods)


1. Inline CSS (One Line in HTML):
○ Where it goes: Inside the opening tag of an HTML element.
○ How it works: Add the style attribute directly to the element.
○ Example:

html

<h1 style="color: blue;">This is a blue heading</h1>

Use: Best for styling a single element.

2. Internal CSS (In the <style> tag within the <head>):


○ Where it goes: Inside the <style> element, placed in the <head> section of the HTML.
○ How it works: Use CSS selectors to target HTML elements.
○ Example:

html

<style>
h1 {
color: red;
}
</style>

Use: Good for styling a single HTML page.

3. External CSS (In a separate .css file):


○ Where it goes: In a separate .css file (like styles.css), linked in the <head> section of your
HTML.
○ How it works: Link to the .css file using a <link> element.
○ Example:

html

<link rel="stylesheet" href="styles.css">

And the contents of styles.css would be:

Css

h1 {
color: green;
}

Use: Perfect for multi-page websites.

Introduction to CSS Page 32


Use: Perfect for multi-page websites.

Exercise Example (Code)


Imagine you re setting up a website with 3 pages to demonstrate these methods. Here’s how the
structure would look like:
1. index.html (links to all three styles)

html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Methods</title>
</head>
<body>
<h1>Choose a style:</h1>
<a href="inline.html">Inline CSS</a>
<a href="internal.html">Internal CSS</a>
<a href="external.html">External CSS</a>
</body>
</html>

2. inline.html (Inline styling)

html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Inline Style</title>
</head>
<body>
<h1 style="color: blue;">This is a blue heading (Inline)</h1>
</body>
</html>

3. internal.html (Internal CSS)

html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Internal Style</title>

Introduction to CSS Page 33


<title>Internal Style</title>
<style>
h1 {
color: red;
}
</style>
</head>
<body>
<h1>This is a red heading (Internal)</h1>
</body>
</html>

4. external.html (External CSS)

html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>External Style</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>This is a green heading (External)</h1>
</body>
</html>

5. styles.css (External CSS file)

css

h1 {
color: green;
}

Summary:
• Inline CSS is quick but not recommended for lots of styles.
• Internal CSS is useful for single-page projects.
• External CSS is the best for multi-page websites and easier to manage.

Introduction to CSS Page 34


Untitled
Saturday, May 3, 2025 11:28 PM

CSS Selectors
✅ What is a CSS Selector?
A CSS selector tells the browser which part of the HTML you want to style.
It’s like pointing at something in a webpage and saying:
“Hey, I want to change you!”

1. Element Selector
• What it does: Targets all elements of a particular HTML tag.
• Syntax:

css

h1 {
color: blue;
}

• Example: Styles all <h1> tags with blue text.

2. Class Selector
• What it does: Targets elements that have a specific class.
• Syntax:

css

.red-text {
color: red;
}

• HTML Example:

html

<h2 class="red-text">Red Heading</h2>

• Note: You can apply the same class to many elements.

3. ID Selector
• What it does: Targets one unique element with an id.
• Syntax:

css

#main {
color: red;
}

Introduction to CSS Page 35


}

• HTML Example:

html

<h2 id="main">Main Heading</h2>

• Note: IDs must be unique on each HTML page.

4. Attribute Selector
• What it does: Targets elements with certain attributes or attribute values.
• Syntax:

css

p[draggable] {
color: red;
}
p[draggable="false"] {
font-size: 20px;
}

• Example:
○ Selects <p> tags that have the draggable attribute.
○ Or selects only those with draggable="false".

• What it does: Selects everything.


• Syntax:

css

*{
margin: 0;
padding: 0;
}

• Use case: Apply a style globally to all elements.

Exercise: Practice with Selectors


Let’s imagine a file called style.css. Your goal is to write C only in this file.

✅ TODO 1: Make All Paragraphs Red


Selector: All <p> tags
Rule:

css

p{

Introduction to CSS Page 36


p{
color: red;
}

✅ TODO 2: Center Text with an ID


Selector: An element with id="main-title"
Rule:

css

#main-title {
text-align: center;
}

✅ TODO 3: Set Font Size for Class


Selector: Elements with class="large-text"
Rule:

css

.large-text {
font-size: 24px;
}

✅ TODO 4: Style Elements with Attribute


Selector: All buttons with disabled attribute
Rule:

css

button[disabled] {
background-color: gray;
}

✅ TODO 5: Apply Style to Elements with Specific Attribute Value


Selector: All images with alt="logo"
Rule:

css

img[alt="logo"] {
width: 100px;
}

Recap
Selector Type Example Used For
Element h1 {} All <h1> tags
Class .btn {} Group of elements

Introduction to CSS Page 37


ID #header {} One specific element
Attribute input[type="text"] {} Elements with certain attributes
Universal * {} Apply to all

Introduction to CSS Page 38


Untitled
Saturday, May 3, 2025 11:31 PM

CSS Color Properties – Beginner Notes


✅ What You Learned
1. CSS Syntax Recap
○ property: value;
Example: background-color: red;
2. Types of Color Properties
○ background-color: Changes the background of an element.
○ color: Changes the text color of an element.
3. Color Value Types
○ Named Colors: Simple, human-friendly names like red, blue, cadetblue, cornflowerblue, etc.
▪ Full list available on MDN Web Docs - Named Colors
○ Hex Codes: Start with # followed by 6 characters (e.g., #5D3891)
▪ Represent Red, Green, and Blue in hexadecimal (base-16)
▪ Each pair (e.g. 5D, 38, 91) represents a value from 0 to 255
4. RGB Breakdown (optional deeper dive)
○ Hex Code #5D3891 = RGB(93, 56, 145)
○ Red = 93/255, Green = 56/255, Blue = 145/255
5. Pro Design Tip: Use Color Palettes
○ Website: ColorHunt.co
○ Choose pre-made color combinations for consistency and beauty

Mini Exercise
You're given a plain HTML file with:

html

<body>
<h1>Hello, CSS!</h1>
< 2>L t’ l t !</ 2>
</body>

Task
Use CSS to:
1. Set the background color of the <body> to antiquewhite
2. Change the <h1> text color to whitesmoke
3. Set the <h1> background color to cornflowerblue
4. Change the <h2> text color using a hex code (choose your favorite!)
5. Set the <h2> background color using a different hex code

✅ Sample Solution
css

body {

CSS Properties Page 39


body {
background-color: antiquewhite;
}
h1 {
color: whitesmoke;
background-color: cornflowerblue;
}
h2 {
color: #6A0DAD; /* Purple text */
background-color: #E0B0FF; /* Lavender background */

CSS Properties Page 40


Untitled
Saturday, May 3, 2025 11:36 PM

CSS Font Properties – Beginner Notes


1. color
• Changes the text color.

css

p{
color: red;
}

2. font-size
Controls how big or small the text appears.
Units of Measurement:
Unit Meaning Approx. Size
px Pixels – tiny square dots (1px ≈ 0.26mm) Static size
pt Points – often used in Word (1pt ≈ 0.35mm) Static size
em Relative to parent's font size Flexible
rem Relative to root (html) font size More consistent

Example:

css

html {
font-size: 20px;
}
body {
font-size: 1rem; /* 20px */
}
h1 {
font-size: 2em; /* 2 × body = 40px */
}

Remember:
• em changes if the parent changes.
• rem stays stable unless the root size (html) changes.

3. font-weight
Sets how bold the text appears.
Values:
• normal = default
• bold = thicker

CSS Properties Page 41


• bold = thicker
• Numeric values: 100 (thin) → 900 (b )
• lighter, bolder = relative to parent

css

p{
font-weight: 700; /* bold */
}

Specifies the typeface.


Syntax:

css

h1 {
font-family: "Times New Roman", serif;
}

Use quotes if the font name has spaces.


Font Types:
• Serif = with decorative strokes (e.g. Times New Roman)
• Sans-serif = no strokes (e.g. Arial, Helvetica)
Always provide a fallback:

css

font-family: Helvetica, sans-serif;

5. Using Google Fonts


Steps:
1. Go to fonts.google.com
2. Choose your font & weight
3. Copy the <link> tag to your HTML <head>
4. Use it in CSS:

html

<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap"
rel="stylesheet">

css

body {
font-family: 'Roboto', sans-serif;
}

Practice Exercises
✅ Exercise 1: Set the root font size and use rems
CSS Properties Page 42
✅ Exercise 1: Set the root font size and use rems
Task: Set html to 16px, and make h1 = 2rem, p = 1rem.

html

<style>
html {
font-size: 16px;
}
h1 {
font-size: 2rem; /* 32px */
}
p{
font-size: 1rem; /* 16px */
}
</style>

✅ Exercise 2: Use em and see it change


Task: Body is 20px. Inside a div, set p to 1.5em.

html

<style>
body {
font-size: 20px;
}
div {
font-size: 20px;
}
div p {
font-size: 1.5em; /* 1.5 × 20px = 30px */
}
</style>

✅ Exercise 3: Set font-family with a fallback


Task: Use "Courier New" with fallback to monospace.

css

code {
font-family: "Courier New", monospace;
}

✅ Exercise 4: Set font-weight using a number


css

strong {
font-weight: 800;

CSS Properties Page 43


font-weight: 800;
}

CSS Properties Page 44


Untitled
Saturday, May 3, 2025 11:39 PM

Topic: CSS Inspection Using Chrome Developer Tools


Objective:
Learn how to inspect and modify CSS live using Chrome Developer Tools, identify applied styles, and
debug layout or style issues.

1. What are Chrome Developer Tools?


• A built-in feature in the Chrome browser used to inspect and edit HTML/CSS in real-time.
• Only available in Chrome, so use Chrome for this course.
• Shortcut keys:
○ Mac: Cmd + Option + I
○ Windows: Ctrl + Shift + I or just press F12

2. Opening the Developer Tools


• Menu Method:
Chrome Menu (⋮) → M →D
• Right-click Method:
Right-click any element →
• Shortcut Keys: Use above based on your OS.

3. Key Tabs in Developer Tools


✅ Elements Tab
• Shows the HTML structure and the applied CSS styles.
• When you select an element, it highlights it in both HTML and browser view.
✅ Styles Section
• Shows CSS rules applied to the selected element.
• You can see which rules are overridden (crossed out).
• Indicates the CSS file and line number (e.g., styles.css).
✅ Computed Tab
• Shows final computed styles (actual values like rgb(0,0,0)).
• Helpful when multiple styles conflict.

4. Live CSS Editing


• You can add, remove, or modify CSS rules temporarily.
• Changes apply only in your browser ( y ’ y )
• Great for testing ideas before updating the real CSS file.

5. CSS Overview Tool


• Go to: DevTools settings (⋮ inside DevTools) → M → CSS Overview
• Shows:
○ Colors used
○ Fonts used
○ Backgrounds
○ Other helpful visual info
• Useful for reverse-engineering websites you like.

CSS Properties Page 45


• Useful for reverse-engineering websites you like.

6. Key Concepts Recap


• Default styles (user-agent stylesheet) come with HTML elements.
• You can override default styles using your own CSS.
• Chrome DevTools lets you see what CSS is active or overridden.
• The Inspector helps understand how other websites are styled.

Exercise: CSS Inspection Challenge


Website to inspect:
https://appbrewery.github.io/css-inspection/
Answer these questions using the Inspector:
1. What is the named color of the body?
○ Inspect <body> → C k b k - →A w : b
2. What is the font size of the h1?
○ Inspect <h1> → C k f - z → A w : 3
3. What is the font weight of the h2?
○ Inspect <h2> → C k f -w → A w : 500
4. What is the font-family of the paragraph tag?
○ Inspect <p> → C k computed styles → A w : A , -serif
✅ Once all are answered, click Submit on the site to check your results.

✅ Summary
Feature What It Does
Elements Tab Inspect HTML and see CSS styles applied
Styles Section Shows all rules, can live-edit
Computed Tab Shows final rendered styles
CSS Overview Summary of fonts, colors, backgrounds, etc.
Live Editing Safe way to test CSS changes without breaking code

CSS Properties Page 46


Untitled
Saturday, May 3, 2025 11:41 PM

Lecture Summary: CSS Box Model & Key Properties


What is the CSS Box Model?
Every HTML element is treated as a box, made up of 4 key layers:
1. Content – The text or image inside the element.
2. Padding – Space inside the box, around the content.
3. Border – Line surrounding the padding.
4. Margin – Space outside the box, between other elements.

1. Width & Height


• Sets the size of the content box.
• Can use px, %, or other units.

css

div {
width: 200px;
height: 150px;
}

2. Border
• Adds a line around the element.
• Takes 3 values: thickness, style, color.

css

div {
border: 5px dashed red;
}
• You can modify specific sides:

css

border-top: 0px;
• Or use shorthand for multiple sides:

css

border-width: 10px 20px 30px 40px; /* top, right, bottom, left */

3. Padding
• Space between content and border.
• Increases the inside space, doesn't affect the actual size (unless box-sizing is changed).

css
CSS Properties Page 47
css

div {
padding: 20px;
}

4. Margin
• Space outside the border.
• Controls distance between elements.

css

div {
margin: 10px;
}

• Like border and padding, margin also follows shorthand:

css

margin: 10px 20px 30px 40px; /* top, right, bottom, left */

Div Element
• <div> = invisible box/container.
• Used to group content.
• No visual by default unless styled.

html

<div>
<p>Text</p>
<img src="..." />
</div>

Developer Tools & Pesticide


• Use Chrome Developer Tools to inspect box model layers (margin, border, padding).
• Use Pesticide Chrome Extension to see all element boundaries clearly.

Exercise
Task:
Style a <div> to look like a content box with the following:
• Width: 200px, Height: 100px
• Padding: 10px
• Margin: 20px
• Border: 5px solid green
Code:
html

CSS Properties Page 48


<div class="box">Hello World!</div>

css

.box {
width: 200px;
height: 100px;
padding: 10px;
margin: 20px;
border: 5px solid green;
}

✅ Output:
A green-bordered box that says "Hello World!" with inner spacing and space from other elements.

CSS Properties Page 49


Untitled
Sunday, May 4, 2025 12:29 PM

Main Idea:
CSS is called Cascading Style Sheets because when multiple rules apply to the same element, the
browser uses a process called the cascade to decide which rule takes effect.

The Four Levels of the Cascade


Think of styles as water in a waterfall: the one at the bottom is what you actually see.
1. Position (Location in code)
• If two rules target the same element and have the same specificity, the one written later (lower
down) wins.
Example:

css

li { color: red; }
li { color: blue; }

The second rule is lower = wins → x b blue.

2. Specificity (How precisely a rule targets an element)


More specific = stronger
Selector Specificity Level Example
Element Lowest li
Class Medium .first-class
Attribute Medium-High [draggable]
ID Highest #first-id

Example:
If a list item has:

html

<li id="first-id" class="first-class" draggable="true">Item</li>


And the CSS says:

css

li { color: blue; }
.first-class { color: green; }
[draggable] { color: purple; }
#first-id { color: orange; }

The ID selector wins → x b orange.

Intermediate CSS Page 50


3. Type of CSS (Where the CSS is written)
Type Priority
External CSS Low
Internal CSS Medium
Inline CSS High

Example:

html

<h1 style="color: red;">Hello</h1>

This inline style will override anything written in external or internal stylesheets.

4. Importance (!important)
Adding !important to a CSS rule makes it the strongest, even stronger than inline styles.
Example:

css

h1 {
color: blue !important;
}

Even if inline style says style="color: red", the !important will win → x blue.

✅ CSS Cascade Decision Checklist:


When CSS rules conflict, follow this order to decide who wins:
1. Importance – Does it use !important?
2. Type – Is it inline, internal, or external?
3. Specificity – How specific is the selector?
4. Position – Which rule comes later in the code?

Quiz Recap
Q1: Which color is applied?
html

<h1 class="title" id="header">Hello</h1>

css

.title { color: blue; }


#header { color: green; }

✅ Answer: Green – ID has higher specificity than class.

Intermediate CSS Page 51


Q2: Which color is applied?
html

<h1 class="a-class another-class">Welcome</h1>

css

.a-class { color: blue; }


.another-class { color: green; }

✅ Answer: Green – Both are classes (same specificity), but the one written later wins.

Tip
W y CSS “ ’ w k ,” k :
• Is another style overriding it?
• Is it written earlier in the file?
• Are you using a more general selector?
• Do you need to be more specific?

Intermediate CSS Page 52


Untitled
Sunday, May 4, 2025 12:39 PM

CSS Selectors & Combining Rules (Beginner Notes)


1. What are CSS Selectors?
CSS selectors let you target specific HTML elements and apply styles to them.
For example:
• p targets all paragraph elements
• .white-text targets any element with the class "white-text"

2. Why Combine Selectors?


Sometimes you want to style only specific parts of your HTML (e.g., a paragraph inside a special box)
without cluttering your HTML with too many class names.

3. Types of Combined Selectors


✅ A. Group Selector (selector1, selector2)
Use this to apply the same style to multiple selectors.
Example:

css

h1, h2 {
color: blueviolet;
}

Targets both <h1> and <h2> elements and makes their text blueviolet.

✅ B. Child Selector (parent > child)


Selects a child element that is one level directly inside the parent.
Example:

css

.box > p {
color: firebrick;
}

Targets only <p> elements that are direct children of an element with class box.
It won’t target nested elements like grandchildren.

✅ C. Descendant Selector (ancestor descendant)


Targets any descendant inside an ancestor, no matter how deep.
Example:

css

Intermediate CSS Page 53


css

.box li {
color: blue;
}

Targets all <li> elements inside any element with class box.
✔ Works even if the <li> is nested multiple levels deep.

✅ D. Chained Selectors (e.g., h1.big.heading)


Targets elements that match all the chained selectors.
Example:

css

h1.big.heading {
font-size: 32px;
}

Targets only <h1> elements with both class big and class heading.
No space allowed between chained selectors.

Exercises
Exercise 1: Group Selectors
Make both the <h1> and <h2> text color blueviolet.

css

h1, h2 {
color: blueviolet;
}

Exercise 2: Child Selector


Turn a <p> inside a .box into firebrick red, but not others.

css

.box > p {
color: firebrick;
}

Exercise 3: Descendant Selector


Make all <li>s inside .box blue, without affecting other list items.

css

.box li {
color: blue;

Intermediate CSS Page 54


color: blue;
}

Exercise 4: Chaining Selectors


Target only an <h1> with classes big and heading.

css

h1.big.heading {
text-transform: uppercase;
}

Summary Table
Selector Type Syntax Targets...
Group h1, h2 Multiple selectors
Child .box > p Direct children only
Descendant .box p Any nested elements inside a parent
Chained h1.big.heading One element matching all selector conditions

Intermediate CSS Page 55


Untitled
Sunday, May 4, 2025 12:41 PM

✅CSS Positioning Notes


What is Positioning in CSS?
Positioning controls how elements appear and move on the web page. Think of your webpage as a
construction site positioning ensures nothing ends up in the wrong place, whether it's a button,
image, or heading.
There are 4 main types of positioning:

ta
• Default positioning.
• Elements appear in the normal flow (one after the other).
• Does not respond to top, left, right, bottom.
Think of it like: Books stacked in a pile. You can't move them unless you pick one up with special
instructions.
CSS Example:

css

div {
t : tat ; /* T d a lt; y d ’t v dt t t */
top: 50px; /* Has no effect */
}

la v
• Element stays in the document flow but you can shift it.
• top, left, right, bottom move it relative to where it would have been.
Think of it like: Moving a sticky note slightly on your monitor, but it still belongs in the same row.
CSS Example:

css

div {
position: relative;
top: 50px;
left: 50px;
}

Use when: You need to nudge elements slightly without breaking layout.

A l t
• Completely removed from the normal flow.
• Positioned relative to the nearest ancestor with a position other than static.
• f , ’ entire page (html).
Think of it like: F b ’ ff
CSS Example:

Intermediate CSS Page 56


CSS Example:

css

.outer {
position: relative;
}
.inner {
position: absolute;
top: 50px;
left: 50px;
}

Key Rule: Always wrap absolute inside a relative container to control where it floats.

d
• Always relative to the browser window (viewport).
• D ’t v when you scroll the page.
Think of it like: Pinning a note to your screen. Scroll the document, it still stays.
CSS Example:

css

div {
position: fixed;
top: 50px;
left: 50px;
}

Use when: You want a sticky navigation bar, floating button, or alert that stays in view.

Bonus: z-index
• Controls which element is "on top".
• Higher z-index = sits above lower ones.

css

div {
position: absolute;
z-index: 100;
}

Note: Only works on positioned elements (relative, absolute, fixed, sticky).

Quick Comparison Table


Position Type In Document Flow? Can Use top/left? Relative To
static ✅ Yes ❌ No
relative ✅ Yes ✅ Yes Its default position
absolute ❌ No ✅ Yes Nearest positioned ancestor

Intermediate CSS Page 57


absolute ❌ No ✅ Yes Nearest positioned ancestor
fixed ❌ No ✅ Yes Browser window

Practice Exercise
HTML:

html

<div class="container">
<div class="box">A</div>
</div>

Tasks:
1. Try each positioning type one by one.
2. Set top: 20px; left: 30px and observe.
3. Add position: relative to .container and position: absolute to .box. See the difference.

Intermediate CSS Page 58


Untitled
Sunday, May 4, 2025 12:45 PM

Lesson: CSS Display Property for Layout


Core Concept
The display property in CSS controls how an HTML element behaves in the layout whether it takes full
width, sits next to others, or disappears altogether.

1. Display: Block
• Default for: <div>, <p>, <h1> etc.
• Behavior: Takes up 100% width of its container, forces next element onto a new line.
• Can set: width, height, padding, margin.
Example:

html

<p style="display: block; width: 200px; height: 200px; background: red;">Block</p>

Think of it like:
A refrigerator that insists on occupying the entire kitchen row by itself.

• Default for: <span>, <a>, <strong> etc.


• Behavior: Stays inline with other elements, does not break to a new line.
• Cannot set: width, height.
Example:

html

<span style="display: inline;">Hello</span><span>World</span>

Think of it like:
Words in a sentence they just flow next to each other.

• Combines features of inline + block


• Behavior: Stays inline, BUT allows width and height control.
Example:

html

<div style="display: inline-block; width: 100px; height: 100px; background: green;"></div>

Think of it like:
Books on a shelf. Each can have its own size, but they still line up next to each other.

4. Display: None
Advanced CSS Page 59
4. Display: None
• Completely hides the element.
• Element won't take space on the page.
Example:

html

<p style="display: none;">This is hidden</p>

Think of it like:
Invisible ink it's there in the code, but y a ’t t at all.

✅ Mini Exercises
Task 1: Align 3 Squares Horizontally
Given: 3 <p> tags, each 200px x 200px.
Goal: Line them up side-by-side (horizontally).
Solution:

css

/* Inside <style> tag */


p{
width: 200px;
height: 200px;
display: inline-block;
}

Why?
inline-block lets the squares sit inline and retain width and height.

Task 2: Align 3 Squares Vertically


Goal: Stack squares top to bottom (vertically).
Solution:

css

p{
display: block;
}

Why?
block elements naturally stack vertically.

Interactive Demo
Visit this page to play around:
appbrewery.github.io/css-display
Try changing display values live and observe layout changes.

Key Takeaways

Advanced CSS Page 60


Display Type Width & Height Aligns Inline? Stacks Vertically?
block ✅ Yes ❌ No ✅ Yes
inline ❌ No ✅ Yes ❌ No
inline-block ✅ Yes ✅ Yes ❌ No (unless forced)
none ❌ Hidden ❌ No ❌ No

Advanced CSS Page 61


Untitled
Sunday, May 4, 2025 12:48 PM

Float Property in CSS - Simplified Notes


What is Float?
• float allows elements (especially images) to "float" to the left or right of their container.
• When an element is floated, text and other inline elements wrap around it.

Why Was Float Created?


• Inspired by newspaper layouts (images with wrapped text).
• The web borrowed this idea to handle image + text side-by-side layouts.

How to Use Float


Example:

css

img {
float: left;
}

➡ This causes text next to the image to wrap around the image on the right side.

Float Values:
Value Effect
left Floats the element to the left
right Floats the element to the right
none Default (no float)

How Float Affects Layout


• Floated elements are taken out of the normal flow.
• This means block elements like <p> or <footer> might appear beside them instead of below.

Problem with Float


When multiple elements are floated, following content (like a footer) may wrap around them, causing
layout issues.

✅ Fix with clear Property


What is clear?
• Tells the browser not to wrap around floated elements.
Example:

Advanced CSS Page 62


css

footer {
clear: both;
}

Clear Value Clears Float From


left Floated-left elements only
right Floated-right elements only
both Both left and right floats

Exercise: Layout Cats and Dogs with Float


Goal:
• Float the cat block to the left and dog block to the right.
• Wrap text around the images inside those blocks.
• Ensure the footer appears below both.

✅ Step-by-Step Solution
css

/* Wrap text around images */


img {
float: left;
margin-right: 10px;
}
/* Float cat block left */
.cat {
float: left;
width: 45%;
background-color: aquamarine;
}
/* Float dog block right */
.dog {
float: right;
width: 45%;
background-color: coral;
}
/* Push footer below both blocks */
footer {
clear: both;
background-color: lightgray;
text-align: center;
padding: 10px;
}

Advanced CSS Page 63


• Cat block on the left, text wraps image.
• Dog block on the right, text wraps image.
• F yb w y q

❗ Modern Practice Tip


Avoid using float for layout designs. Instead, use:
• Flexbox
• CSS Grid
• Frameworks like Bootstrap
Use float only when wrapping text around an image.

Advanced CSS Page 64


Untitled
Sunday, May 4, 2025 12:50 PM

CSS Responsive Layout - Beginner Notes


✅ What is Responsive Design?
• It means your website adapts to any screen size (desktop, tablet, phone).
• Try resizing your browser window to see how websites adjust their layout.
• Goal: Make content look good on all devices.

4 Main Methods to Make a Website Responsive

1. Media Queries
Used to apply CSS rules only at certain screen sizes.
How it works:
• You write a CSS rule like this:

Css

CopyEdit@media (max-width: 600px) {


nav {
display: none;
}
}

This means:
If screen is 600px or less, hide the navigation bar.
✅ Use different breakpoints for different devices (mobile, tablet, etc.).

2. CSS Grid
Used to create 2D layouts (rows + columns).
How it works:
• First, set container:

css

.container {
display: grid;
grid-template-columns: 1fr 1fr;
grid-template-rows: 100px 200px 200px;
gap: 30px;
}

• 1fr = 1 equal part


• 2 columns: each takes 50%
• 3 rows: 100px, 200px, 200px
• gap = space between grid items
Make a card span 2 columns:

Advanced CSS Page 65


Make a card span 2 columns:

css

.first {
grid-column: span 2;
}

3. Flexbox
Used for 1D layouts (only row or only column).
How it works:

css

.container {
display: flex;
}
.card {
flex: 1;
height: 100px;
}

➡ flex: 1 means equal width for all cards


➡ You can customize:

css

.card1 { flex: 2; } /* 2x width */


.card2 { flex: 0.5; } /* Half width */
Flexbox is great for making layouts adjust automatically, based on screen size.

4. Bootstrap (External Framework)


• A library of ready-made CSS classes for layout & design.
• You link it from their website, then use their class names like:

html

<div class="container">
<div class="row">
<div class="col">...</div>
<div class="col">...</div>
</div>
</div>

• Bootstrap handles media queries and responsiveness for you.


• Great for building fast and responsive designs without writing too much CSS.

Exercise: Try It Yourself


Objective: Create a layout that:
• Shows 2 boxes side by side on large screens
• Stacks boxes on top of each other on small screens

Advanced CSS Page 66


• Stacks boxes on top of each other on small screens
HTML:

html

<div class="box-container">
<div class="box">Box 1</div>
<div class="box">Box 2</div>
</div>

CSS:

css

.box-container {
display: flex;
}
.box {
flex: 1;
padding: 20px;
background-color: lightblue;
border: 1px solid blue;
text-align: center;
}
@media (max-width: 600px) {
.box-container {
flex-direction: column;
}
}

➡ Resize your browser to test it!

Advanced CSS Page 67


Untitled
Sunday, May 4, 2025 12:52 PM

Responsive Design with Media Queries – Beginner Notes

What is a Media Query?


A media query is a CSS feature used to apply styles only if certain conditions are met (like screen size). It
helps make your website responsive.
Syntax:

css

@media (condition) {
/* CSS styles */
}

Basic Keywords
1. @media – starts the media query.
2. max-width – targets screens up to a certain width (e.g., mobile).
3. min-width – targets screens from a certain width (e.g., desktop).
4. and – used to combine conditions.
5. screen – optional keyword to target screen devices (vs. print for printers).

Key Concept: Breakpoints


Breakpoints are screen widths where your layout/design should change.
Common breakpoints:
Device Width Range
Mobile 319px – 480px
Tablet/iPad 481px – 1200px
Laptop 1201px – 1600px
Desktop 1601px and above

Example: Basic Media Query


Default style

css

div {
width: 200px;
height: 200px;
background-color: blue;
}

Media Query for Mobile

Advanced CSS Page 68


css

@media (max-width: 600px) {


div {
width: 100px;
height: 100px;
}
}

Combining Conditions
Target devices between 600px and 900px:

css

@media (min-width: 600px) and (max-width: 900px) {


/* styles here */
}

• screen → f ( f )
• print → f f
Example:

css

@media print {
body {
background: white;
color: black;
}
}

Exercise
Task: Change body background color based on screen size.
Requirements:
• Mobile: 319–480 x →
• Tablet: 481–1200 x → w b
• Laptop: 1201–1600 x →
• Desktop: 1601px and up →
• Default: aquamarine

✅ Solution Code
css

body {
background-color: aquamarine;
}
/* Mobile */

Advanced CSS Page 69


/* Mobile */
@media (max-width: 480px) {
body {
background-color: salmon;
}
}
/* Tablet */
@media (min-width: 481px) and (max-width: 1200px) {
body {
background-color: powderblue;
}
}
/* Laptop */
@media (min-width: 1201px) and (max-width: 1600px) {
body {
background-color: limegreen;
}
}
/* Desktop */
@media (min-width: 1601px) {
body {
background-color: seagreen;
}
}

Testing Responsiveness
Use Chrome Developer Tools:
• Press Ctrl + Shift + I or right-click → " "
• Click on the device toolbar icon ( )
• Switch between devices or use custom width

Advanced CSS Page 70


Untitled
Sunday, May 4, 2025 2:34 PM

Flexbox Basics – Beginner-Friendly Notes


1. Why Flexbox?
• Websites used to be designed like newspapers: simple columns and rows.
• Earlier methods included:
○ <table>: Used to layout websites with <tr> (table row) and <td> (table data). ❌ Not good
for design anymore, only use for tabular data!
○ display: inline-block: Allowed boxes to line up next to each other, but alignment was messy.
○ position: absolute: Floats elements on top, but not flexible for dynamic content.
○ float: Helped with wrapping text around images or sidebars, but very hacky for layouts.

2. Flexbox to the Rescue


• Designed specifically to make layout easy and responsive.
• Introduced to fix issues from older methods.

• First step: Make a container flexible.

css

.container {
display: flex;
}

• Children inside the container become flex items.


• Flexbox ignores their default display settings (block, inline, etc).

4. Flex Container Properties


• display: flex: Turns a container into a flexbox.
• gap: Adds space between flex items.

css

gap: 1rem; /* Responsive spacing */

• display: inline-flex: Makes the container behave like inline-block.

5. Other Key Flexbox Features (Coming Later)


• justify-content: Align items horizontally.
• align-items: Align items vertically.
• flex-direction: Controls whether items go in a row or column.
• flex-wrap: Allows items to wrap onto the next line.

Exercise – Turn a Vertical List into a Horizontal Navbar


Goal: Change a vertical menu list to a horizontal navigation bar using Flexbox.
Your HTML:

FlexBox Page 71
Your HTML:

html

<div class="container">
<ul>
<li>Home</li>
<li>About</li>
<li>Contact</li>
<li>Blog</li>
</ul>
</div>

✅ Step-by-step CSS Solution:

css

ul {
list-style: none; /* remove bullet points */
padding: 0;
margin: 0;
display: flex; /* make the <ul> a flex container */
gap: 20px; /* add space between <li> items */
}

TIP: You apply display: flex to the ul, not the lis. That turns the list into a row!

Summary
Technique Good for Avoid for
<table> Tabular data Page layout
inline-block Basic alignment Complex layouts
float Text wrap Modern layouts
Flexbox Layouts, spacing

FlexBox Page 72
Untitled
Sunday, May 4, 2025 2:21 PM

✅ Key Concepts: Flex Direction in Flexbox

1. Default HTML Flow


• Inline elements flow left to right until they wrap.
• Block elements stack top to bottom by default.

2. Flex Container
When you apply display: flex to a container:
• All children become flex items.
• By default, Flexbox arranges items in a row (left to right).

3. The flex-direction Property


This controls which direction the items are placed in the flex container.
Value Main Axis Cross Axis
row (default) left → top ↓ b
column top ↓ b left →

• flex-direction: row; → H z y
• flex-direction: column; → V y

4. Main Axis vs Cross Axis


These terms define the direction in which Flexbox "flexes".
• Main axis = direction of items
• Cross axis = perpendicular to main axis
Example:

css

.container {
display: flex;
flex-direction: column;
}

Now the main axis is vertical, so all items stack top to bottom.

5. flex-basis
• Sets the initial size of a flex item along the main axis.
○ In row → width
○ In column → height
So:

css

FlexBox Page 73
.container > * {
flex-basis: 100px;
}

If flex-direction: column, each item will be 100px tall.

6. Targeting Child Elements with CSS


Use this to style all children of a Flex container:

css

.container > * {
/* applies to all direct children */
}

• > = child combinator


• * = universal selector (targets all types of elements)

7. inline-flex vs flex
• display: flex; → k full width
• display: inline-flex; → y k as much width as needed

Exercise Summary
Goal:
Change a default horizontal Flexbox layout into a vertical one with each item 100px tall.
Given:
HTML:

html

<div class="container">
<div>Red</div>
<div>Orange</div>
<div>Yellow</div>
...
</div>

Solution in CSS:
css

.container {
display: inline-flex; /* shrink to fit content */
flex-direction: column; /* stack top to bottom */
}
.container > * {
flex-basis: 100px; /* each item is 100px tall */
}

FlexBox Page 74
}

Try This Yourself


1. Change flex-direction to row, row-reverse, column-reverse
2. Adjust flex-basis values
3. Switch between flex and inline-flex
4. Use DevTools to observe main vs cross axis live

FlexBox Page 75
Untitled
Sunday, May 4, 2025 2:35 PM

CSS Flexbox: Flexible Layouts & Key Properties


Understanding Parent vs Child in Flexbox
• Parent = Flex container → w y
• Child = Flex items → ff by ’
’ very important to know which property goes where parent or child.

order – Rearranging Flex Items


• Default behavior: Flex items appear in HTML order.
• You can change the visual order using order.
Example:

css

.green {
order: 3;
}
• All items default to order: 0.
• Larger order = item moves further right (in a row layout).

flex-wrap – Handling Overflow


• Default: flex-wrap: nowrap (items overflow and get cut off).
• To allow wrapping to the next line:

css

.container {
flex-wrap: wrap;
}

• wrap-reverse → w reverse direction (bottom to top, right to left).


Set on parent.

justify-content – Main Axis Alignment


Controls horizontal alignment (if flex-direction: row).

css

.container {
justify-content: center; /* or flex-start, flex-end, space-between, space-around, space-evenly
*/
}

✅ Examples:

FlexBox Page 76
✅ Examples:
• flex-start: items aligned left.
• center: items in the middle.
• space-between: equal spacing between items.
• space-around: equal space around items.
• space-evenly: equal space between and around.
Set on parent.

align-items – Cross Axis Alignment


Controls vertical alignment (if flex-direction: row).

css

.container {
align-items: center; /* or flex-start, flex-end, stretch, baseline */
}

Requires height to be set on the container.

align-self – Override for Individual Items


Lets a single flex item break from group alignment.

css

.item-special {
align-self: flex-start;
}

Use when one child needs different alignment than others.

Visual Summary
Property Axis Set On Effect
order N/A Child Reorders items visually
flex-wrap Main Parent Controls wrapping of child items
justify-content Main Parent Horizontal distribution
align-items Cross Parent Vertical alignment of all items
align-self Cross Child Vertical alignment of one item

Exercise
HTML:

html

<div class="container">
<div class="box red">Red</div>
<div class="box green">Green</div>
<div class="box blue">Blue</div>

FlexBox Page 77
<div class="box blue">Blue</div>
</div>

CSS Task:
1. Set display: flex and flex-direction: row.
2. Make the .green box appear last using order.
3. Make all items wrap when screen is small.
4. Align all items to the bottom.
5. Make .blue float to the top (use align-self).

FlexBox Page 78
Untitled
Sunday, May 4, 2025 2:39 PM

Lecture Notes: Flexbox Sizing and Responsiveness


Flexbox Recap
• Flex Container: An element with display: flex.
• Flex Items: All children of a flex container.
When we put block elements like <p> inside a flex container:
• They become inline by default (i.e., line up horizontally).
• They shrink and grow automatically based on available space.

How Flexbox Determines Item Size (The Sizing Priority List)


Flexbox uses the following order of importance to decide item size:
1. min-width and max-width (top priority)
2. flex-basis (preferred size on the main axis)
3. width or height (based on axis)
4. Content width (default fallback)

Content-Width Behavior (No Size Set)


If you set no width or sizing:
• The content decides the width.
• Flex items will shrink until the longest word still fits.
• Beyond that, items get pushed off-screen.

Setting width
css

.item {
width: 100px;
}

• Sets a fixed width for each item.


• Works until the container can’t fit all items.
• Then, it shrinks items but still respects the longest word.

Using flex-basis
css

.item {
flex-basis: 200px;
}

• Tells Flexbox the ideal size.


• Ignores width if both are set.
• Still shrinks if there's not enough space.

FlexBox Page 79
• Still shrinks if there's not enough space.
✅ Remember: flex-basis > width

Setting max-width
css

.item {
flex-basis: 200px;
max-width: 100px;
}

• Item will shrink to 100px even if there's room for 200px.


• max-width limits growth, even beyond flex-basis.

Setting min-width
css

.item {
flex-basis: 200px;
min-width: 300px;
}

• Flex item will not shrink below 300px.


• min-width overrides smaller flex-basis.
✅ Remember: min-width > flex-basis

Practice Exercise
HTML
html

<div class="container">
<p class="item">Short</p>
<p class="item">Medium text</p>
<p class="item">ReallyReallyLongWordWithoutSpaces</p>
</div>

CSS
css

.container {
display: flex;
gap: 10px;
}
.item {
flex-basis: 150px;

FlexBox Page 80
flex-basis: 150px;
max-width: 200px;
min-width: 100px;
}

✅ What Happens?
• Tries to make each item 150px.
• Won’t go above 200px.
• Won’t go below 100px.
• The long word forces a minimum width based on that word.

Summary
Property Controls Overrides
min-width Smallest allowed size Everything smaller
max-width Largest allowed size flex-basis, width
flex-basis Preferred size (main axis) Overrides width
width Fallback size (if nothing else) Content width
Content width Based on text or elements Last fallback

FlexBox Page 81
Untitled
Sunday, May 4, 2025 3:09 PM

CSS Grid: Introduction & Flexbox Comparison


What is CSS Grid?
• CSS Grid is a layout system for building two-dimensional layouts on the web (both rows and
columns).
• It's like putting items into a table where you control the size and position of each cell.

Flexbox vs Grid
Flexbox Grid
One-dimensional layout Two-dimensional layout
Works in a row OR column Works in rows AND columns
Good for small UI elements Great for full page layouts

Use Flexbox for:


• Navbars
• Centering content
• Horizontal or vertical lists
Use Grid for:
• Web pages with complex structure
• Dashboards, image galleries, etc.
✅ Most websites combine both: Grid for structure, Flexbox for aligning items within grid cells.

Key Concepts in CSS Grid


1. Display: grid
• Turns the container into a grid layout.
2. grid-template-columns / grid-template-rows
• Defines how many columns/rows there are and their sizes.
Example:

css

.container {
display: grid;
grid-template-columns: 1fr 2fr;
grid-template-rows: 1fr 1fr;
}
• Creates a layout with:
○ 2 columns (2nd column is twice as wide)
○ 2 equal-height rows
3. fr (fractional unit)
• A flexible unit for defining column/row sizes.
• 1fr 2fr = 1 part and 2 parts of the available space.
4. gap
• Controls spacing between rows and columns (like margin).

Grid Page 82
css

gap: 10px;

HTML Setup

html

<div class="container">
<div class="white"></div>
<div class="black"></div>
<!-- ...repeat 64 times -->
</div>
Your Goal:
• Create an 8x8 chessboard using CSS Grid.
• Each square: 100px x 100px
✅ Solution:

css

.container {
display: grid;
grid-template-columns: repeat(8, 100px);
grid-template-rows: repeat(8, 100px);
}
.white {
width: 100px;
height: 100px;
background-color: #f0d9b5; /* Light tile */
}
.black {
width: 100px;
height: 100px;
background-color: #b58863; /* Dark tile */
}

What You Learned:


• How Grid simplifies complex layouts.
• Difference between Flexbox and Grid.
• How to define columns and rows using grid-template-columns/rows.
• Use of fr, gap, and repeat() for efficiency.
• Real-world example: building a chessboard with clean, minimal code.

Grid Page 83
Untitled
Sunday, May 4, 2025 3:11 PM

Goal: Learn how to size rows and columns in CSS Grid to match
your layout needs.

1. Fixed Sizing
• Use pixels (px) or rem to set exact sizes.

css

grid-template-rows: 100px 200px;


grid-template-columns: 400px 800px;
• Not responsive: Doesn’t adjust to screen size changes.
• REM is based on the root font-size (1rem = 16px by default), but still behaves as fixed width unless
the root font-size changes.

2. Shorthand: grid-template
You can write both rows and columns like this:

css

grid-template: 100px 200px / 400px 800px;


• Rows come first, then a slash /, then columns.
• Useful in other people's code, but not beginner-friendly. Better to stick with separate grid-
template-rows and grid-template-columns.

3. Auto Sizing
css

grid-template-columns: 200px auto;


grid-template-rows: 100px auto;
• auto columns: stretch to fill the remaining width.
• auto rows: adjust to fit the content only, not screen height.
✅ Good for flexible layouts.

4. Fractional Units (fr)


css

grid-template-columns: 1fr 2fr;


grid-template-rows: 1fr 2fr;
• fr = a fraction of available space.
• 1fr 2fr → w w f
• Responsive: adjusts as the screen size changes.

Grid Page 84
5. MinMax Function
css

grid-template-columns: 1fr minmax(400px, 800px);


• Sets a range: column can shrink to 400px or grow up to 800px.
• Helpful to avoid content being too squished or too stretched.

6. Repeating Rows/Columns
css

grid-template-rows: repeat(2, 200px);


grid-template-columns: repeat(2, 100px);
• Repeats the same size multiple times.
• Saves time and keeps code cleaner.

7. Too Many or Too Few Items?


• If your grid has more cells than items, empty cells remain unused.
• If you have more items than defined cells, extra items still appear:
○ They will continue in the next available row or column.
○ You can control the style of those extra cells using:

css

grid-auto-rows: 300px;
grid-auto-columns: 150px;

Exercise
Try this grid layout and observe the behavior:

html

<div class="grid-container">
<div>1</div><div>2</div><div>3</div><div>4</div><div>5</div>
</div>

css

.grid-container {
display: grid;
grid-template-columns: repeat(2, 200px);
grid-template-rows: repeat(2, 150px);
grid-auto-rows: 100px;
gap: 10px;
}
• How many rows will appear?
• What height will the 5th item have?
✅ Expected: 3 rows; the third one is auto-created with 100px height.

Grid Page 85
Untitled
Sunday, May 4, 2025 3:06 PM

Understanding Grid Item Placement in CSS Grid


You Can Use Multiple Grid Cells for One Item
A grid item can span across multiple cells both horizontally and vertically.
Example:
• One item can take up 2 columns
• Another can span 2 rows
This allows for flexible and complex layouts.

Grid Lines (Invisible But Crucial)


• Grid lines are the invisible lines between the columns and rows.
• You cannot style them (no color, no content).
• You can only control the space between them using the gap property.

css

gap: 3rem; /* Adds spacing between rows and columns */

This eliminates the need for using margin or padding to separate grid items.

Basic Grid Setup


Creating a Grid Container
You start by defining a grid container:

css

.container {
display: grid;
height: 100vh; /* Makes it full screen vertically */
}
• display: grid enables Grid mode.
• 100vh means the container takes up the full height of the viewport.

Defining Tracks (Rows and Columns)


Use grid-template-columns and grid-template-rows to define tracks:

css

grid-template-columns: 1fr 1fr 1.5fr; /* 3 columns: last one is wider */


grid-template-rows: 1fr 1fr; /* 2 rows: equal height */

Each fr unit represents a fraction of available space.

Default Placement of Grid Items


Grid Page 86
Default Placement of Grid Items
If you add 3 items (e.g., .cowboy, .astronaut, .book), Grid will place them:
• From left to right
• Into the first available cells
No manual positioning needed unless specified.

Centering Content Inside Grid Items (Using Flexbox)


To center content (e.g., emojis) inside a grid item, use Flexbox inside each item:

css

.item {
display: flex;
justify-content: center; /* center horizontally */
align-items: center; /* center vertically */
}

Tip: Flexbox is perfect for aligning items within grid items. Use both together!

Customizing Item Layout with Grid Lines


Span Multiple Columns Using grid-column
css

.cowboy {
grid-column: span 2; /* spans two columns */
}

Equivalent to:

css

grid-column-start: auto;
grid-column-end: span 2;
This tells the grid item to start at the default position and span across 2 columns.

Use Specific Line Numbers


You can also explicitly tell items where to start and end:

css

grid-column-start: 2;
grid-column-end: 4;

Or using negative indexing from the right side:

css

grid-column-end: -1; /* last line on the right */

Grid Page 87
grid-column-end: -1; /* last line on the right */
: 1 f last line w b f

You Can Reverse the Order!


Start and end lines can be written in any order:

css

grid-column-start: 4;
grid-column-end: 2;

The browser automatically handles the direction based on line numbers.

Just like horizontal span, you can span rows:

css

grid-row-start: 1;
grid-row-end: 3; /* spans two rows */

Or simply:

css

grid-row: span 2;

Summary of Terms
Term Meaning
Container The element with display: grid
Item The children inside the grid container
Cell A single unit where an item can sit
Track A column or row
Line Borders between tracks
Gap Space between lines (not visible lines)

Challenge Practice
Task: Center each emoji using Flexbox inside the grid items.

css

.emoji-item {
display: flex;
justify-content: center;
align-items: center;
}

Grid Page 88
}

Use Grid to define your layout, and Flexbox to fine-tune alignment.

Grid Page 89
Untitled
Sunday, May 4, 2025 3:15 PM

Introduction to Bootstrap
What is Bootstrap?
Bootstrap is a popular CSS framework created in 2010 by Twitter developers Mark Otto and Jacob
Thornton.
A CSS framework is a pre-written set of CSS code that helps us build responsive, beautiful
websites faster.

Why Use Bootstrap?


Benefit Explanation
Pre-Built Components Buttons, cards, forms, navbars already styled and ready to use
Mobile First Designed to work on both mobile and desktop
12-Column Layout Easy to create responsive designs using Flexbox
⚡ Fast & Easy Add classes instead of writing custom CSS
Widely Used Powers around 80% of websites using frameworks

Real Example
HTML Button Without Bootstrap

html

<button>Home</button>

→L k
HTML Button With Bootstrap

html

<button class="btn btn-primary btn-lg">Home</button>

→L k y , , y

How to Use Bootstrap?


1. Include Bootstrap CSS via CDN in <head>:

html

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet">

2. (Optional) Include Bootstrap JS (for dropdowns, etc.) before </body>:

Bootstap Page 90
html

<script src="https://cdn.jsdelivr.net/npm/bootstrap@
5.3.0/dist/js/bootstrap.bundle.min.js"></script>

What are Cards?


Cards are ready-made components for displaying content like images, text, and buttons.
Example:

html

<div class="card" style="width: 18rem;">


<img src="flower.jpeg" class="card-img-top" alt="Sunflower">
<div class="card-body">
<h5 class="card-title">Card Title</h5>
<p class="card-text">Some example text.</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>

Pros vs Cons
✅ Pros
• Easy to use
• Saves time
• Pre-made UI components
• Good for quick projects
• Works well on all browsers
❌ Cons
• Class Bloat: Too many class names in HTML
• Harder to customize every detail
• May rely too much on framework, less on core CSS learning

Exercise: Bootstrap Card Setup


✅ Objective:
Upgrade a plain HTML site using Bootstrap to show a styled card with a flower image.

1. Add Bootstrap CSS link in the <head>.


2. Insert the Bootstrap Card HTML inside <body>.
3. Fix the image path to use flower.jpeg.
4. Use Flexbox to center the card on screen.

✅ Final Result:
A fully styled Bootstrap card with a sunflower image, centered both vertically and horizontally.

Solution:

Bootstap Page 91
html

<!-- STEP 1: Head Section -->


<head>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet">
<style>
body {
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
</style>
</head>
<!-- STEP 2: Card HTML -->
<body>
<div class="card" style="width: 18rem;">
<img src="flower.jpeg" class="card-img-top" alt="Sunflower">
<div class="card-body">
<h5 class="card-title">Card Title</h5>
<p class="card-text">Some example text.</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
</body>

Bootstap Page 92
Untitled
Sunday, May 4, 2025 3:16 PM

Bootstrap 12-Column Grid System


1. Basic Layout Structure
To create a Bootstrap layout, always follow this 3-step structure:

html

<div class="container">
<div class="row">
<div class="col">Your content here</div>
</div>
</div>

• container: This wraps the entire layout and sets padding/margins.


• row: This ensures your columns align horizontally.
• col: This sets your content into responsive columns.

2. How Columns Work


Bootstrap divides the row into 12 equal columns.
• If you use 6 columns (col), each takes up 1/6 of the row.
• If you use 3 columns, each takes up 1/3 of the row.
• Use col-N to control how many columns a div spans (e.g., col-4 = 4/12 = 33%).

html

<div class="col-2">2/12</div>
<div class="col-4">4/12</div>
<div class="col-6">6/12</div>

Together, they fill 12/12 of the row.

3. Responsive Breakpoints
Use breakpoints to control how content looks on different devices:
Class Applies On Screens Wider Than
col-sm- 576px (small phones)
col-md- 768px (tablets)
col-lg- 992px (laptops)
col-xl- 1200px (desktops)
col-xxl- 1400px (large screens)

Example:

html

Bootstap Page 93
<div class="col-sm-12 col-md-6 col-lg-4">Content</div>

• On small phones → 100%


• On tablets → 50%
• On laptops → 33%

4. Fluid Containers
• container: Fixed width with responsive breakpoints.
• container-fluid: Full width (100%) on all screen sizes.
• container-md: Full width starting from medium screens (≥768px).

5. Mixing Columns and Auto Layout


You can:
• Set specific sizes: col-4
• Let Bootstrap auto-balance: col (without number)
• Mix both in one row.

html

<div class="col-2">2</div>
<div class="col-4">4</div>
<div class="col">auto</div>

Here, the last column takes the remaining space.

6. Multiple Breakpoints in One Column


Example:

html

<div class="col-sm-12 col-md-8 col-lg-4">Content</div>

• Small screens: 100%


• Medium screens: 66%
• Large screens: 33%
Useful for progressively reducing column size as the screen widens.

✅ Practice Exercise
Task:
Create 2 divs inside a row:
• Each div should be 50% on desktop (XL)
• And 100% on mobile (SM)
✅ Solution:
html

<div class="container">
<div class="row">

Bootstap Page 94
<div class="row">
<div class="col-sm-12 col-xl-6">Box 1</div>
<div class="col-sm-12 col-xl-6">Box 2</div>
</div>
</div>

✅ Explanation:
• col-sm-12: Full width on small screens.
• col-xl-6: Half width (6/12 = 50%) on desktops.

Tip
If no width is defined (col), Bootstrap auto-splits the row evenly among the columns. But if screen size is
smaller than the defined breakpoint, all columns will stack vertically.

Bootstap Page 95
Untitled
Sunday, May 4, 2025 3:31 PM

W at’ D t T M d l ?
• Until now, we focused on functionality HTML and CSS to build websites.
• N w, w ’ f design making websites look beautiful and user-friendly.

Why Design Matters


• ’ w b f j w k w they notice if it looks good.
• Good design = positive emotional reaction from users.

Real Example: Penny Juice Website


• Original Website:
○ Clashing colors, too many fonts.
○ Result: Users are only willing to pay $1 for the juice.
• Redesigned Website:
○ Consistent colors, clean typography.
○ Result: Users are willing to pay $3 for the same product.
Lesson: Good design can triple the perceived value of a product!

Why First Impressions Matter


• “D ’ j b k by ” ’ f w b
• You have just 3 seconds to make a great impression.
• Think of it like a first date or job interview visuals matter instantly.

Takeaway: Design is a Smart Investment


• Cheap to learn, big impact.
• Makes your brand or product look more premium and trustworthy.

W at Y ’ll L a N t
1. Color Theory – choosing colors that work together.
2. Typography – using fonts effectively.
3. UI Design (User Interface) – designing buttons, forms, and layout.
4. UX Design (User Experience) – creating smooth, pleasant user journeys.

✅ Exercise
Question: Look at one of your favorite websites.
1. Write down the first 3 design features that catch your eye (e.g., colors, layout, fonts).
2. Then write:
○ What feeling does the design give you (trust, fun, professional)?
○ Would you pay more for a product from that website? Why?

WEB design school Page 96


Untitled
Sunday, May 4, 2025 3:33 PM

Web Design Module: Color Theory Made Simple


What Is Color Theory?
Color Theory is both the art and science of choosing colors that work well together and send the right
message on your website.

Why Colors Matter


Colors affect how users feel about your website and how much they value your product.
Example:
• Ugly website? People might pay $1 for juice.
• Beautiful website? They’re willing to pay $3.

Color & Emotion Guide


Color Message It Sends Common Uses
Red Love, energy, intensity Cars, fast food, excitement
Yellow Joy, intellect, grabs attention Headlines, ads, warning messages
Green Freshness, nature, safety Food, health, environment
Blue Trust, peace, stability Banks, fintech, social media
Purple Royalty, luxury, femininity Fashion, cosmetics, loans for women

Color Combinations
1. Analogous Colors
○ Colors next to each other on the color wheel (like red + orange).
○ Best for calm, smooth designs (e.g., navbar + background).
○ ✅ Harmonious, ❌ Doesn’t pop much.
2. Complementary Colors
○ Opposites on the color wheel (like red + green).
○ Great for highlights, logos.
○ ✅ High contrast, ❌ Not good for text + background combos (too jarring).
3. Triadic Palette
○ 3 colors forming a triangle on the color wheel.
○ Balanced and colorful (good for playful themes).
4. Square Palette
○ 4 colors equally spaced around the color wheel.
○ More complex, vibrant designs.

Tools to Use
• Adobe Color – Try different palettes like Analogous, Triadic, etc.
• ColorHunt.co – Ready-made color palettes by designers.

Practice Exercise
WEB design school Page 97
Practice Exercise
Task: Choose the best color palette for each website type from the options below.
1. Bank Website
• A. Red + Yellow
• B. Blue + Grey
• C. Purple + Pink
2. Organic Grocery Store
• A. Green + Light Brown
• B. Red + Black
• C. Yellow + Purple
3. Fitness App
• A. Blue + Orange
• B. Pink + Green
• C. Grey + Dark Purple

✅ Solutions
1. B – B = → f f f
2. A – G =N /F → f
3. A – B =S b y, O = y→ f f

WEB design school Page 98


Untitled
Sunday, May 4, 2025 3:36 PM


✅ Why Typography Matters
• Typography isn't just about choosing a favorite font.
• The font you use sends a message and creates a mood just like colors.
• The wrong font can make your design look unprofessional or send the wrong signal (e.g.,
romantic message in a horror font!).

Font Families – The Big Two


1. Serif Fonts
• Have little "feet" or lines at the ends of letters.
• Inspired by stone carving, w 90° w ’ b
• Give off a mood of:
○ Seriousness
○ Tradition
○ Authority
• Good for:
○ Legal firms, architecture magazines, historical themes.
Subcategories of Serif:
Subtype Style Description Example Use
Old Style Softer contrast (thick/thin parts) Wine labels, classic vibes
Transitional Moderate contrast Balanced style
Modern Strong contrast Fashion magazines (e.g., Vogue)
Slab Serif Block-like serifs Strong, bold branding

The more contrast between thick and thin, the more modern the font looks.

2. Sans-Serif Fonts
• No feet, clean ends.
• Look simple, friendly, modern, and approachable.
• Better for:
○ Websites
○ Startups
○ Body text (more readable)
Subcategories of Sans-Serif:
Subtype Traits Examples
Humanist Natural, readable shapes Gill Sans, Tahoma, Verdana
Grotesque Rigid, less readable Akzidenz-Grotesk, Franklin Gothic

Fun Fact:
A study at MIT showed that drivers read dashboards faster when Humanist fonts were used vs.
Grotesque 30–40% faster, potentially saving lives!

WEB design school Page 99


• Readability = How pleasant/easy it is to read blocks of text.
• Legibility = How easy it is to distinguish individual letters.
What helps?
• Open shapes (e.g., 'o' not too closed)
• Space between letters
• Clear difference between similar characters (e.g., ‘g’ vs ‘9’, ‘O’ vs ‘0’)

Combining Fonts (The Smart Way)


• D ’t t a y t – Stick to 2 per design (e.g., heading + body).
• Combine:
○ Serif + Sans-serif for contrast.
○ Bold + Light weights for interest.
• Keep moods similar:
○ D ’ x y w f
Rule of thumb: Contrast the style (serif vs sans-serif), but match the mood and era.


Some fonts are hard to work with and look unprofessional:
• Comic Sans
• Papyrus
• Curlz MT
• Jokerman
• Bradley Hand
• Vivaldi
Only use them if your target audience is 5 years old or you're running a lemonade stand .

Exercise
Task: Design a simple quote poster using the following:
• One serif font for the quote.
• One sans-serif f f ’
• Use different weights (bold/light).
• Try matching the mood of both fonts (e.g., both serious, or both modern).
Example:
"Design is intelligence made visible."
Alina Wheeler
(Use Playfair Display for the quote and Open Sans for the author)

WEB design school Page 100


Untitled
Sunday, May 4, 2025 3:41 PM

User Interface Design: Key Concepts


1. Hierarchy: What's Important First?
• What is it?
○ Hierarchy is about deciding what’s most important and making it stand out!
○ Our brains naturally focus on larger, bolder, or more prominent items.
• Example:
○ Imagine a birthday invite with everything the same size – super confusing!
○ Better Design: Make key info (who, where, when) bigger and brighter.
• How to establish hierarchy:
○ Color: Use bold, contrasting colors! A bright button will pop on a muted background.

○ :B = ! H b !
• Real-life Example:
○ ASOS uses green/red to grab attention on important actions like Add to Cart.

2. Layout: How Things Are Arranged!


• What is it?
○ Lay t y wy a a v yt
• Example of Poor Layout:
○ Wikipedia has long lines of text, making it hard to read.
○ Optimal Line Length: Around 40-60 characters per line. Makes reading smooth!
• Good Layout Example:
○ Grammarly uses varied content blocks, making it fun and easy to read! ✨

3. Alignment: Keeping Everything Neat!


• What is it?
○ Alignment is about lining up your design elements in a consistent way.
• Example:
○ Left-aligned vs center-aligned? If misaligned, things look messy!
○ Proper alignment makes designs look polished and professional.
• Design Tip:
○ Fewer alignment points = more cohesion. Keep things neat and sharp!

W t a : v T t at !
• What is it?
○ White space is the empty space around elements that makes them stand out.
• How it works:
○ Luxury Branding uses lots of space to look expensive.
○ = B t a = !
• Example:
○ A l ’ ad use minimal text and big white space to make their products feel premium.

5. Designing for Your Audience: Who Are You Designing For?


• What is it?

WEB design school Page 101


• What is it?
○ Always know who you are designing for. Tailor your style to their needs!
• Example:
○ Children's concert poster = bright and fun.
○ Corporate event poster = sleek and formal.
• Flexibility in Design:
○ Design should be t d for your audience (teenagers vs medical pros).

Practical Tips
• Apply hierarchy to highlight the important stuff.
• Mix up your layout to keep things interesting!
• Align elements to create a polished look.
• Use white space to make things look clean and modern. ✨
• Always consider your audience and design for them.

Exercises
1. Exercise 1: Redesign a birthday invite
○ Apply hierarchy: Bold colors, varied sizes.
○ Solution: Make the title bold, date and time prominent, and location secondary.
2. Exercise 2: Evaluate a webpage (e.g., Wikipedia)
○ Suggest a better layout.
○ Solution: Shorten line lengths to 40-60 characters, add images, and space out sections.
3. :L at a d t ad
○ Suggest using white space to improve it.
○ Solution: Remove excess text, space out features, and make the product image the focus.

Takeaway
• UI Design is about making things easy to use, visually appealing, and tailored to your audience.

• Always use hierarchy, good layout, alignment, white space, and audience awareness to create
top-notch designs! ✨

WEB design school Page 102


Untitled
Sunday, May 4, 2025 3:44 PM

User Experience Design (UX)


What is UX?
• Think of UX as the invisible friend that makes everything feel easy on a website.

Story Time: Reed College Renovation


• Imagine a college renova ng its campus.
• A famous architect renovates everything but forgets paths. ❌
• The architect comes back a er a year, at are formed by people naturally walking!
• This represents User Experience – it adapts based on how people use it, instead of just a "pretty"
design. ✨

Five Key Principles of UX


1. l ty: L M !
○ Too many things on a page can make your brain go .
○ Example: Sina News website = way too cluttered.
○ Monocle News = clean, simple, easy to digest.
○ ess n: t l ! educe clu er!
2. Consistency: Keep it Steady!
○ Example: Xfinity's website has inconsistent navigation buttons.
○ Users get confused.
○ Lesson: Consistent design means less confusion and frustration.
3. Reading Patterns: F and Z!
○ Humans read in specific patterns, like the F-pattern or Z-pattern.
○ a : Le to right, top to bo om.
○ a : igzagging across.
○ Lesson: Design for the eye's natural path!
4. All Platform Design: Desktop & Mobile!
○ Example: Facebook's redesign takes up too much empty space on a wide desktop.
○ ess n: Make sure your design works v y :M l D t .
5. Testing: Always Test!
○ D ’ !G d a f
○ Lesson: Test early and often for the best results.

• Dark patterns ky k w ’ b f f b b
harmful to the user.
Examples of Dark Patterns:
1. Wa t a d w k f ,b ’ air
2. Amazon's Delivery Button - Always trying to get you to pay more for Express Delivery.
3. Snapchat Ad - C k " " ’ y k
4. ya a ’ t aC a - Hidden dropdowns make it hard to opt-out of travel insurance.
5. Confusing Checkboxes - "Stop not sending you deals" – what?!
• Remember: Good UX is about helping users, not tricking them!

WEB design school Page 103


Final Test: Apply What You've Learned!
• It’s time to design a hotel website using all these principles. ✨
• Design for simplicity, consistency, reading patterns, and all platforms while avoiding dark
patterns!

Takeaway:
• User Experience should be invisible, like paved paths that let people move around easily.
• Keep things simple, consistent, and user-friendly to ensure a delightful experience. ✨

WEB design school Page 104


Untitled
Thursday, August 14, 2025 12:22 AM

JavaScript: The Language that Powers the Web


What is JavaScript?
• A scripting language that runs in browsers to make websites dynamic & interactive.
• Without JS → w b = , -time interaction.

History & Origins


• 1990s → B w w Mosaic, then Netscape Navigator (Marc Andreessen).
• Netscape once had 80% market share → x “B w W ”
• Netscape tech → Firefox later.
• Netscape wanted more dynamic, interactive web pages → Brendan Eich.
• Eich created JavaScript in just 10 days (originally called LiveScript).

Why JavaScript Matters


• Runs inside the browser (no server round-trips needed).
• Made the web interactive (animations, input validation, real-time feedback).
• Works on all browsers →
• Today → w front-end + back-end (Node.js) + mobile + even Web3.

The Web Without JavaScript


• Try disabling JS in Chrome →
○ ❌ Twitter → N , f
○ ❌ YouTube & Netflix → W ’
○ ✅ NYTimes → N ( y JS)
• Lesson: The modern web is heavily dependent on JS.

Why Called JavaScript?


• Originally LiveScript.
• Renamed in 1995 because “Java” a t t d (marketing move).
• Relationship to Java?
○ Java vs JavaScript ≈ Car vs Carpet
○ Java = compiled language, JS = interpreted scripting language.

ECMAScript Standard (ES)


• Many versions of JS → f
• Standardized as ECMAScript (ES) by European Computer Manufacturers Association.
• ’ w yy ES6, ES7 instead of JS6, JS7.

How Scripting Works (Analogy)


• Script = Play script .
• Actors = HTML elements.
• Example:
○ First unhide <h1> → 1 y→ < >→ x “H W ”
• Lesson: JS tells HTML elements what to do, when, and how.

Popularity & Usage


• JavaScript = consistently most popular language (RedMonk ranking).

Introudction to JS ES6 Page 105


• JavaScript = consistently most popular language (RedMonk ranking).
• Used across:
○ Frontend (React, DOM, animations)
○ B k (N j , AP )
○ Mobile (React Native)
○ W b3 (B k , DA , NF )

Takeaway
• JavaScript = the backbone of modern web development.
• Essential for building interactive, responsive, and real-time apps.
• Learn JS first if you want to build websites & web apps.

Introudction to JS ES6 Page 106


Untitled
Wednesday, September 3, 2025 6:58 AM

Your First JavaScript Code


⚡ Goal: Learn how to add behavior to websites using JavaScript.

Using the JavaScript Console in Chrome


1. Open Chrome → V w > D >J S C
2. Type alert("Hello"); → P Enter → P - w “H ”
○ ✅ OK dismisses pop-up.
3. Issue: Writing multi-line code is tricky.
○ Enter = runs code immediately.
○ Use Shift + Enter to move to next line.
○ Example:

alert("Hello");
alert("World");
○ First pop-up → "H ", → "W "

Snippets = Better Way to Run Code


• Go to Sources tab → Snippets (hidden gem ✨).
• Click + New Snippet → xj
• Write multi-line JS like a mini file:

alert("Hello!");
alert("World");
• H (b )→ x by
• ✅ Console = quick testing, Snippets = writing reusable scripts.

Errors & Keywords


• Example: say("Hello") ❌ → B w w:
Uncaught ReferenceError: say is not defined.
• W y? y ’ z keyword/function.
• ✅ Use real commands (like alert).

Finding Valid Commands


• Use MDN Web Docs → S JavaScript → , ()
• Docs show:
○ window.alert("Message") (full)
○ alert("Message") (shortcut).
• Helps you learn syntax + behavior.

Breaking Down alert("Hello");


• alert → k yw (f )= -up behavior.
• "Hello" → ( x q )
• ;→ = f ( k )
• () → =w f

Programming Grammar

Introudction to JS ES6 Page 107


Programming Grammar
• Symbols (quotes, semicolons, brackets) = grammar rules.
• Mistakes = browser confusion.
• Example:
○ Quotation marks in Word/Docs = ❌ fancy symbols.
○ Quotes in code editor = ✅ correct syntax.

Style & Best Practices


• ✅ No spaces in alert("Hello"); → +
• ✅ Use double quotes for strings ("Hello") → JS y
• Later, single quotes ' ' are useful in certain cases.
• Bookmark JavaScript Style Guides → consistent code.
○ Key principle: “All c de sh uld l k like a single pers n wr te it.”

Analogy
• ; = period in English.
• "Hello" = text string, not code.
• Programming languages = different grammar rules (JS vs Python vs Ruby).

Takeaway
• Console = test 1 line.
• Snippets = write real scripts.
• Use MDN for valid keywords/functions.
• Follow style guides → , f

Introudction to JS ES6 Page 108


Untitled
Wednesday, September 3, 2025 7:03 AM

JavaScript Data Types


Recap from Last Lesson
• We used alert("Hello"); → pop-up.
• Browser needs to know:
○ W ’ code (alert)
○ W ’ text ("Hello")

Strings
• Defined using quotation marks " "
• Everything inside quotes = string (text data)
• Example:

alert("Hello World");
• C “ ”b ’ string of characters, like a string of pearls.
• Found in all programming languages.

Numbers
• Just type them (no quotes needed).
• Example:

2 + 3 // → 5

• B w k w ’ number because of digits (not letters).

l a
• Data that is either true or false.
• Example:

true
false
• Essential for logic & conditions.

The typeof() Keyword


• Use typeof to check a data type.
• Examples:

typeof 23 // "number"
typeof "Angela" // "string"
typeof true // "boolean"

Playground (Console Experiments)


• Try in Chrome console:
○ 2+3→5
○ alert(2 + 3) → P -up with 5
○ typeof "Hello" → " "
typeof false → "b "

Introudction to JS ES6 Page 109


○ typeof false → "b "

Takeaway
• Programming = dealing with different types of data.
• Main primitive types in JS:
○ String (text)
○ Number
○ B ( /f )
• Data types = foundation block for websites & web apps.

Next Lesson Preview → V b ( storing data).

Introudction to JS ES6 Page 110


Untitled
Wednesday, September 3, 2025 7:04 AM

JavaScript Variables & Prompt


A al y (A la’ I t )
• J k b A ’ , y, b →y ’ f y
time.
• Programming does the same → w store info in variables so the computer remembers it.

prompt() Keyword
• Creates a pop-up like alert(), but allows user input.
• Example:

prompt("What is your name?");


• W → f

Variables
• Used to store data in memory.
• Example:

var myName = "Angela";


• Now typing myName in console → "A "

Syntax Breakdown

var variableName = value;


• var → k yw ( w /b x)
• variableName → b f b x ( , yN )
• =→ ( b x)
• value → ( , "A ")
• ;→ f

Why called variable


• Contents can change.
• Example:

myName = "Jack";
• Now the same box stores "Jack" instead of "Angela".

I ta t l
• Use var only when creating a variable.
• D ’ w changing/updating it.

Challenge Example
• Show variable value with alert:

alert(myName);

User Input + Storage

Introudction to JS ES6 Page 111


User Input + Storage
• Combine prompt() with variables:

var yourName = prompt("What is your name?");


alert("My name is " + myName + ", welcome to my course " + yourName + "!");

Practical Example: Game Level

var gameLevel = 1;
gameLevel = 2;
alert("Your level is currently: " + gameLevel);
• Start with 1, update as game progresses.
• Computer remembers value in the variable.

Takeaway
• Variables = storage boxes for data.
• prompt() = ask user for input, store inside variable.
• No need to repeat → j f b

Introudction to JS ES6 Page 112


Exercise 1
Wednesday, September 3, 2025 7:06 AM

Initial Setup
var a = 3;
var b = 8;
// Write your code here

Step-by-Step Thinking
1. You a ’t d tly a a and b because you’d overwrite one of them.
Example:

a = b; // now a = 8, but b is still 8 → w 3

2. Just like with buckets of sand and water, you need a temporary container to hold one value while
switching.

Solution
var a = 3;
var b = 8;
// Your code
= ; // ’ (3) f y
a = b; // now a becomes 8
b = temp; // b takes the saved 3

Output
console.log("a is " + a); // a is 8
console.log("b is " + b); // b is 3
✅ This works, follows all rules:
• No changing existing code
• No typing numbers
• No redeclaring a or b

Introudction to JS ES6 Page 113


Untitled
Wednesday, September 3, 2025 7:09 AM

Notes: Swapping Variables in JavaScript


Problem
We have two variables:

var a = 3;
var b = 8;
Goal → Sw =8 b=3

❌ What NOT to Do
• D ’ :

var a = 8; var b = 3; // ❌ breaks rule


• D ’ y y b :

a = 8; b = 3; // ❌ not allowed
• D ’ b :

var a = "8"; var b = "3"; // ❌ invalid

✅ Correct Solution
Use a temporary variable as a placeholder, like a spare bucket:

var temp = a; // Save a (3)


a = b; // Put b (8) into a
b = temp; // Put saved 3 into b
Now:

a→8
b→3

Key Takeaway
• Think of variables as containers (or buckets).
• When swapping, you need a third container to temporarily hold data.
• Logic first → y x

Interview Tip:
This problem is a classic coding interview question. The interviewer cares more about your reasoning
process ( “b k y”) j f y x

Introudction to JS ES6 Page 114


Untitled
Wednesday, September 3, 2025 7:23 AM

JavaScript Strings & Concatenation


What is a String?
• A string = text inside quotation marks (" " or ' ').
• Example:

"Hello"
'World'

➕ Concatenation (Joining Strings)


• Use the + operator to join strings together.
• Example:

"a" + " " + "b" // → " b"


"hello" + "world" // → " w "
"hello" + " world" // → " w "

Only the parts inside quotes are combined.

Challenge: Greeting Message


1. Create two variables:

var message = "Hello";


var name = "Angela"; // or prompt("What is your name?");
2. Combine them in an alert using concatenation:

alert(message + " " + name);


// → "H A "

b :A ""b w w !

✅ Key Takeaways
• Strings can be joined with +.
• Spaces must be manually added inside strings (" ") or before/after variables.
• You can combine variables + strings in alerts, prompts, or console logs.

Introudction to JS ES6 Page 115


Untitled
Wednesday, September 3, 2025 7:24 AM

JavaScript Strings – Length Property & Character


Counter
length Property
• Every string in JavaScript has a .length property.
• It returns the number of characters in the string.

var name = "Angela";


console.log(name.length); // 6

Twitter Example (140 Characters)


• Old Twitter limit = 140 characters (now 280).
• Use .length to track characters used and remaining.

Challenge Code: Twitter Character Counter


var tweet = prompt("Compose your tweet:");
var tweetCount = tweet.length;
alert(
"You have written " + tweetCount + " characters, " +
"you have " + (140 - tweetCount) + " characters remaining."
);
✅ Works with any input string.
✅ Shows negative remaining characters if over the limit.

• If you dismiss the prompt, tweet becomes null.


○ null.length → : Cannot read property 'length' of null
• To avoid this, always enter some value in the prompt.

Comments in JavaScript
• Single-line comment: // text
• Multi-line comment:

/*
This is a
multi-line comment
*/

✅ Key Takeaways
• .length tells you how many characters are in a string.
• Can be used to build features like word/character counters.
• Comments (// or /* */) are useful to document code.

Introudction to JS ES6 Page 116


Untitled
Wednesday, September 3, 2025 7:26 AM

JavaScript Strings – Slice & Character Limit


.slice() Method
• Extracts part of a string without changing the original.
• Syntax:

string.slice(startIndex, endIndex);
• Returns characters from startIndex up to but not including endIndex.
x (z b )

Examples
var name = "Angela";
name.slice(0, 1); // "A" → f
name.slice(5, 6); // "a" →
name.slice(0, 3); // "Ang" → 0,1,2
name.slice(1, 5); // "ngel" → 1,2,3,4

Quick tip: number of characters = end - start.

Twitter Character Limit Example


Goal → C w w 140 characters max.
Longer Version (step by step):

var tweet = prompt("Compose your tweet:");


var tweetUnder140 = tweet.slice(0, 140);
alert(tweetUnder140);
Shorter One-Liner:

alert(prompt("Compose your tweet:").slice(0, 140));

✅ Key Takeaways
• .slice(0, 140) → x f 140
• Perfect for enforcing input limits (like Twitter).
• Can shorten multi-line code into one-liners by nesting functions.

Introudction to JS ES6 Page 117


Exercise 2
Wednesday, September 3, 2025 7:28 AM

We want a program that:


1. Prompts the user for their name (input may be all lowercase, uppercase, or mixed).
2. Outputs an alert like:

Hello Angela

✅ First letter = uppercase


✅ Rest of letters = lowercase

Step-by-Step Breakdown
1 tt ’ a
var name = prompt("What is your name?");
2. Extract the first letter (index 0)
var firstChar = name.slice(0,1);
3. Extract the rest of the name (everything after index 0)
var restOfName = name.slice(1, name.length);
4. Format properly
• First char →
• Rest → w

firstChar = firstChar.toUpperCase();
restOfName = restOfName.toLowerCase();
5. Recombine
var capitalizedName = firstChar + restOfName;
6. Display greeting
alert("Hello, " + capitalizedName);

✅ Full Code
var name = prompt("What is your name?");
var firstChar = name.slice(0,1);
var restOfName = name.slice(1, name.length);
firstChar = firstChar.toUpperCase();
restOfName = restOfName.toLowerCase();
var capitalizedName = firstChar + restOfName;
alert("Hello, " + capitalizedName);

⚡ One-liner (advanced)
Introudction to JS ES6 Page 118
⚡ One-liner (advanced)
If you want to shrink it:

alert("Hello, " + prompt("What is your name?").slice(0,1).toUpperCase() +


prompt("What is your name?").slice(1).toLowerCase());
(but that calls prompt twice, so the clean multi-step version is better ).

Introudction to JS ES6 Page 119


Untitled
Wednesday, September 3, 2025 7:31 AM

Notes – Capitalizing First Letter in JavaScript


Problem
Capitalize only the first letter of a user’s name, while ensuring the rest is lowercase.

1. Get User Input


var name = prompt("What is your name?");
• Prompt stores user input into a variable.
• Example: "angela"

2. Isolate First Character


var firstChar = name.slice(0, 1);
• .slice(0,1) → x f y
• Example: "a"

3. Convert First Character to Uppercase


var upperCaseFirstChar = firstChar.toUpperCase();
• Example: "A"

4. Isolate Rest of the Name


var restOfName = name.slice(1, name.length);
• Takes everything after the first character.
• Example: "ngela"

5. Normalize Rest of Name (Edge Case Fix)


restOfName = restOfName.toLowerCase();
• Ensures even if user typed weird casing ("angELA") → b " "

6. Concatenate for Final Capitalized Name


var capitalizedName = upperCaseFirstChar + restOfName;
• Example: "Angela"

7. Display Greeting
alert("Hello, " + capitalizedName);
• Output: "Hello, Angela"

Introudction to JS ES6 Page 120


If you skip .toLowerCase() → x
Example: Input "angELA" → "A LA" (w )

✅ Key Lesson
Programming = breaking problems down into smaller chunks.
• Big problem → b b → fy by
• Test with edge cases → k f f

Takeaway
• .slice(start, end) → x f
• .toUpperCase() & .toLowerCase() → x
• Always test with edge cases (weird user input).
• The process of breaking down problems is more important than memorizing shortcuts.

Introudction to JS ES6 Page 121


Untitled
Wednesday, September 3, 2025 7:36 AM

Steps
1. Get user’s name with prompt()
2. Capitalize first letter
3. ➕ Concatenate first letter + rest of name
4. Greet user with alert()

Breaking Down the Problem


t t
var name = prompt("What is your name?");

I lat t aa t
var firstChar = name.slice(0, 1);
• slice(0, 1) → k y f

Ma tl a
var upperCaseFirstChar = firstChar.toUpperCase();

t t t a
var restOfName = name.slice(1, name.length);

Ma tl a ( d t)
restOfName = restOfName.toLowerCase();

C at at al a
var capitalizedName = upperCaseFirstChar + restOfName;

t
alert("Hello, " + capitalizedName);

Full Code
var name = prompt("What is your name?");
var firstChar = name.slice(0, 1);

Introudction to JS ES6 Page 122


var firstChar = name.slice(0, 1);
var upperCaseFirstChar = firstChar.toUpperCase();
var restOfName = name.slice(1, name.length);
restOfName = restOfName.toLowerCase();
var capitalizedName = upperCaseFirstChar + restOfName;
alert("Hello, " + capitalizedName);

Key Takeaways
• Break big problems into small steps
• slice(start, end) → x f
• .toUpperCase() → k
• .toLowerCase() → k w
• Concatenation (+) → j
• Always test for edge cases

Introudction to JS ES6 Page 123


Untitled
Wednesday, September 3, 2025 7:38 AM

Numbers in JavaScript
➕ B
• Add: +
• Subtract: -
• Multiply: *
• Divide: /

2 + 3 // 5
7 - 4 // 3
5 * 2 // 10
10 / 2 // 5

• 9%6→3( f 9 ÷ 6)
• 6%4→2
• 12 % 8 → 4
✅ Use case: check even/odd

if (num % 2 === 0) {
console.log("Even");
} else {
console.log("Odd");
}

Operator Precedence
• Multiply & divide before add & subtract

3 + 5 * 2 // 13
(3 + 5) * 2 // 16
Use parentheses → & f

Dog Age
Formula:
(dogAge−2)×4+21( A − 2) × 4 + 21( A −2)×4+21
Code:
var dogAge = prompt("How old is your dog?");
var humanAge = ((dogAge - 2) * 4) + 21;
alert("Your dog is " + humanAge + " years old in human years.");
Example:
• Dog = 7 → H = 41

Takeaways
Introudction to JS ES6 Page 124
Takeaways
• %→ ( f / k)
• Always think about order of operations
• Use () parentheses for clarity
• Prac ce with small challenges (like Dog Age converter )

Introudction to JS ES6 Page 125


Untitled
Wednesday, September 3, 2025 7:39 AM

Why Functions?
• Imagine a robot (Angela) → -by-step instructions to get milk
• Without functions → f ❌
• With functions → k one block ✅

Function Structure
function getMilk() {
console.log("leaveHouse");
console.log("moveRight");
console.log("moveUp");
console.log("buyMilk");
console.log("moveDown");
console.log("moveLeft");
console.log("enterHouse");
}
Parts:
• function → k yw f
• getMilk → ( C )
• () → (f )
• {}→ yb (b k f )

getMilk();
• No function keyword here → j by
• Runs everything inside { }

alert vs. console.log


• alert("message") → w
• console.log("message") → f f ( b )
Switch to console.log when testing → k OK y !

Style Tips
• Indent code inside { } for readability
• Closing curly brace does not end with ;
• Function calls (getMilk();) do end with ;

Takeaways
• Functions = reusable blocks of instructions
• Define once, call many times → k D Y (D ’ Y f)
• Use console.log for developer messages, alert for user messages

Introudction to JS ES6 Page 126


Untitled
Wednesday, September 3, 2025 7:41 AM

Karel the Robot – Functions & Challenges


Setup
• Karel lives in a 5x5 grid
• Default entry point:

function main() {
// your code here
}
• Basic commands:
○ move() → f w
○ turnLeft() → 90° f
○ putBeeper() → b
○ pickBeeper() → k b

Example: Move & Turn


function main() {
move();
move();
move();
turnLeft();
}
All code inside main() runs when you press Run.
Custom Function
function goInCircle() {
move();
turnLeft();
move();
turnLeft();
move();
turnLeft();
move();
turnLeft();
}
function main() {
goInCircle(); // call function
}
Functions = reusable blocks → k D Y

Challenge 1: Reach Top-Right (5x5)


function moveFourTimes() {

Introudction to JS ES6 Page 127


function moveFourTimes() {
move();
move();
move();
move();
}
function main() {
moveFourTimes();
turnLeft();
moveFourTimes();
}
Karel ends in top-right corner.

Challenge 2: Diagonal Beepers


Goal → b yf b -left ↗ top-right.

function diagonalMoveAndBeeper() {
move();
turnLeft();
move();
putBeeper();
turnRight(); // custom turnRight function can be written
}
function turnRight() {
turnLeft();
turnLeft();
turnLeft();
}
function main() {
putBeeper(); // first tile
diagonalMoveAndBeeper();
diagonalMoveAndBeeper();
diagonalMoveAndBeeper();
diagonalMoveAndBeeper();
}

Optional Challenge: Chessboard Pattern


• Alternate les with beepers
• Requires smart use of functions + loops.

Takeaways
• main() = starting point
• Functions help remove repetition (DRY principle)
• Break problems into smaller reusable steps
• Start with simple moves → b b
Next lesson: Functions with inputs (parameters)

Introudction to JS ES6 Page 128


Untitled
Wednesday, September 3, 2025 7:42 AM

Functions with Inputs (Parameters)


Recap: Vanilla Functions
• Just a block of code that runs when called.

function sayHello() {
console.log("Hello!");
}
sayHello(); // "Hello!"

Chocolate Flavor: Functions with Inputs


• Functions can accept inputs → parameters.
• Inputs are like temporary variables inside the function.
Example: Bottles Input
function getMilk(bottles) {
var cost = bottles * 1.5;
console.log("Buy " + bottles + " bottles of milk.");
console.log("Cost: $" + cost);
}
getMilk(2);
// → B y 2 b f k
// → C : $3

Input (2) is bound to parameter (bottles).

Challenge: Use Money Instead of Bottles


Goal → b b y yb b w y

function getMilk(money) {
var numberOfBottles = Math.floor(money / 1.5);
console.log("Buy " + numberOfBottles + " bottles of milk.");
}
getMilk(5);
// → B y 3 b f k

Math.floor() ensures we round down (no fractional bottles ).

⚡ Key Takeaways
• Parameters = function inputs (like variables).
• Use them to make functions flexible.
• Math.floor() is handy when you need whole numbers.
• fy ’ k→G /f ( k round down JS).

Introudction to JS ES6 Page 129


Untitled
Wednesday, September 3, 2025 7:44 AM

Goal
Write a function lifeInWeeks(age) → :

You have X days, Y weeks, and Z months left.

1. Assume:
○ 365 days/year
○ 52 weeks/year
○ 12 months/year
○ Lifespan = 90 years
2. Calculate remaining years:

let yearsRemaining = 90 - age;


3. Derive totals:

let days = yearsRemaining * 365;


let weeks = yearsRemaining * 52;
let months = yearsRemaining * 12;
4. Output exact sentence ( , ,f ):

console.log("You have " + days + " days, " + weeks + " weeks, and " + months + " months left.");

✅ Full Function
function lifeInWeeks(age) {
let yearsRemaining = 90 - age;
let days = yearsRemaining * 365;
let weeks = yearsRemaining * 52;
let months = yearsRemaining * 12;
console.log("You have " + days + " days, " + weeks + " weeks, and " + months + " months left.");
}

Example Run
lifeInWeeks(12);
Output:

You have 28470 days, 4056 weeks, and 936 months left.

Introudction to JS ES6 Page 130


Untitled
Wednesday, September 3, 2025 7:47 AM

BMI Calculator (JS)


Formula
BMI = weight / (height²)
• weight → kg
• height → meters

Function (weight first, then height)


function bmiCalculator(weight, height) {
return weight / (height ** 2);
}

var bmi = bmiCalculator(65, 1.8);


console.log(bmi); // 20.061728395...

Optional: Round for display (keeps raw value if needed)


function bmiCalculator(weight, height) {
return weight / (height ** 2);
}
var bmi = bmiCalculator(72, 1.74);
console.log(Number(bmi.toFixed(1))); // 23.8

Notes
• Order matters: bmiCalculator(weight, height) ✅
• Use meters (e.g., 170 cm → 1 70)
• ** is exponent; you can also use Math.pow(height, 2)

Introudction to JS ES6 Page 131


Untitled
Wednesday, September 3, 2025 7:49 AM

BMI Calculator Recap


Formula
BMI=weightheight2BMI = \frac{weight}{height^2}BMI=height2weight
• t→k
• height →

Step 1: Define Function


function bmiCalculator(weight, height) {
var bmi = weight / (height * height);
return bmi;
}
✅ ( × f )

Step 2: Power Operator (Alternative)


function bmiCalculator(weight, height) {
var bmi = weight / Math.pow(height, 2);
return bmi;
}
Math.pow(height, 2) → w f2

Step 3: Round Result


function bmiCalculator(weight, height) {
var bmi = weight / Math.pow(height, 2);
return Math.round(bmi);
}
✨ Math.round() → w b

Example Usage
var bmi = bmiCalculator(65, 1.8);
console.log(bmi); // 20

Takeaway
• function → f b b k
• return → b k
• Math.pow() → x
• Math.round() →
• Always test with realistic inputs ✅

Introudction to JS ES6 Page 132


Untitled
Wednesday, September 3, 2025 7:55 AM

Adding JavaScript to Websites


Up to now → y console (pure JS).
Now → JS HTML page.

Setup
• Folder → DOM/
• Files:
○ index.html
○ styles.css (blank for now)
○ index.js (later)

⚡ 3 Ways to Add JavaScript


1. Inline JavaScript ❌ (bad practice)
<body onload="alert('Hello');">
<h1>Hello</h1>
</body>
P b :
• Hard to debug
• Not modular
• Avoid if possible

2. Internal JavaScript
<script>
alert("Hello");
</script>
• JS is written inside <script> tags
• Executes as browser parses the HTML

3. External JavaScript ✅ (best practice)


<script src="index.js"></script>
Code lives in index.js:

alert("Hello");

Placement Matters
• CSS → < >( y before content)
• JavaScript → bottom of <body> (after HTML is created)
Example:
<body>

The Document Object Model (DOM) Page 133


<body>
<h1>Hello</h1>
<script src="index.js"></script>
</body>
✅ Works → b < 1> x b f
f< > < >, JS y y ’ →

Example: Changing Text


index.js

document.querySelector("h1").innerHTML = "Good Bye";


• ✅ Works if <script> is after <h1>
• ❌ Fails if <script> runs before <h1> is loaded

Best Practices
• Put <script> just before </body>
• Keeps site fast (HTML loads first, JS later)
• External JS files keep code clean & reusable

The Document Object Model (DOM) Page 134


Untitled
Wednesday, September 3, 2025 7:56 AM

DOM (Document Object Model) Basics


What is the DOM?
• Browser turns HTML + CSS → DOM tree
• Every HTML element = an object in the tree
• Tree has parent–child & sibling relationships
Example HTML:

<html>
<head></head>
<body>
<h1>Hello</h1>
<button>Click Me</button>
</body>
</html>
DOM tree (simplified):

document
html
head
body
h1
button

Navigating the DOM


document; // whole page
document.firstElementChild; // <html>
document.firstElementChild.firstElementChild; // <head>
document.firstElementChild.lastElementChild; // <body>

Selecting & Manipulating Elements


1. Save selection in variable
var heading = document.firstElementChild.lastElementChild.firstElementChild;
2. Change content
heading.innerHTML = "Good Bye"; // changes <h1>Hello</h1> → < 1>G By </ 1>

3. Change style
heading.style.color = "red";

The Document Object Model (DOM) Page 135


Query Selectors
document.querySelector("h1"); // selects first <h1>
document.querySelector("input"); // selects first <input>
document.querySelector("ul li"); // selects first <li> inside <ul>

Properties vs Methods
• Properties = describe object

car.color = "red"; // property


console.log(car.color); // getter
• Methods = actions object can perform (functions tied to object)

car.drive(); // method
document.querySelector("input").click(); // simulates a click
Properties → ()
Methods → w y ()

Challenge
Select the 3rd <li> and change its text to your name (via console, not HTML).
Solution hint
document.querySelector("ul li:nth-child(3)").innerHTML = "Your Name";

Takeaway
• DOM = bridge between HTML/CSS ↔ J S
• Use dot notation to access properties/methods
• Manipulate HTML on the fly = interactivity

The Document Object Model (DOM) Page 136


Untitled
Wednesday, September 3, 2025 8:41 AM

DOM Selection in JavaScript


1. getElementsByTagName()
• Selects all elements with a given tag name.
• Returns an HTMLCollection (array-like).

document.getElementsByTagName("li"); // all <li>


document.getElementsByTagName("li")[2].style.color = "purple"; // 3rd <li>
console.log(document.getElementsByTagName("li").length); // count

2. getElementsByClassName()
• Selects all elements with a given class.
• Also returns an array-like collection.

document.getElementsByClassName("btn")[0].style.color = "blue";

3. getElementById()
• Selects a single element by its id.
• Ids must be unique per page.

document.getElementById("title").innerHTML = "Good Bye";

4. querySelector()
• Returns the first matching element.
• Accepts CSS-style selectors:
○ h1 → by
○ #id → by
○ .class → by
○ Combine: "li.item", "ul#list li a"

document.querySelector("h1"); // first h1
document.querySelector("#title"); // element with id="title"
document.querySelector(".btn"); // element with class="btn"
document.querySelector("ul#list li a"); // <a> inside list

5. querySelectorAll()
• Returns all matching elements (NodeList).

document.querySelectorAll("li.item"); // all li with class="item"


document.querySelectorAll("li.item")[1].style.color = "green"; // 2nd one

Key Differences
• t l t y… → b ,
• querySelector / querySelectorAll → f x b , CSS ,

The Document Object Model (DOM) Page 137


• querySelector / querySelectorAll → f x b , CSS ,

Challenge Recap
Change the Google link inside the list to red:

document.querySelector("li a").style.color = "red";

Takeaway
• Use querySelector/querySelectorAll in most cases (flexible, powerful).
• By f y k w ’ y q
• Always remember: collections need indexing before style changes.

The Document Object Model (DOM) Page 138


Untitled
Wednesday, September 3, 2025 8:43 AM

Manipulating CSS with JavaScript (DOM Style)


Selecting & Styling
• Use .style to change CSS of an element:

document.querySelector("h1").style.color = "red";

CamelCase vs CSS kebab-case


• CSS → f -size
• JS → f S z
• Rule: remove dashes ➝ capitalize next word ✅
Example:

document.querySelector("h1").style.fontSize = "10rem";

Remember
• Values must be strings in JS ("10rem", "yellow", "7%").
• Even numbers with units must be quoted.

Challenge Example (button background)


CSS way:

button {
background-color: yellow;
}
JavaScript way:

document.querySelector("button").style.backgroundColor = "yellow";

Practice Ideas
• Try toggling:

document.querySelector("h1").style.visibility = "hidden";
• Change spacing:

document.querySelector("h1").style.padding = "20px";
• Play with multiple properties via DevTools console.

Next Lesson
• Separation of Concerns
Keep styles in CSS and just toggle/add/remove classes with JavaScript ⚡.

The Document Object Model (DOM) Page 139


Untitled
Wednesday, September 3, 2025 8:44 AM

Separation of Concerns in Web Development


• HTML → C
• CSS → S y
• JavaScript → B ⚡
Bad practice:

document.querySelector("h1").style.color = "red";
This mixes behavior + style.

✅ Better Way: classList


Every DOM element has a .classList property.
Useful Methods:
• .add("className") →
• .remove("className") →
• .toggle("className") → w / ff

Example: Hide Button


CSS:
.invisible {
visibility: hidden;
}
JS:
var button = document.querySelector("button");
button.classList.add("invisible"); // hides button
button.classList.remove("invisible"); // shows button
button.classList.toggle("invisible"); // toggles visibility

Challenge: Make Text Huge


CSS:
.huge {
font-size: 10rem;
color: red;
font-weight: bold;
}
JS:
document.querySelector("h1").classList.add("huge");
One line of JS applies multiple styles by simply attaching the class.

The Document Object Model (DOM) Page 140


Key Takeaways
• Keep styles in CSS.
• Use JS only to add/remove/toggle classes.
• Easier debugging:
○ Style issue? → k CSS
○ Behavior issue? → k JS

The Document Object Model (DOM) Page 141


Untitled
Wednesday, September 3, 2025 8:46 AM

innerHTML vs textContent in JavaScript


innerHTML
• Returns or sets HTML inside the element.
• Includes tags + text.
• Can inject HTML dynamically.

<h1 id="title"><strong>Hello</strong></h1>

document.querySelector("#title").innerHTML;
// Output: "<strong>Hello</strong>"
document.querySelector("#title").innerHTML = "<em>Good Bye</em>";
// Renders: *Good Bye* (italicized)
M t ""b ’

textContent
• Returns or sets only the text, no tags.
• Safer if you just want raw text.

document.querySelector("#title").textContent;
// Output: "Hello"
document.querySelector("#title").textContent = "Good Bye";
// Renders: Good Bye (plain text, no HTML effect)

✨ Key Differences
• innerHTML → x + HTML tags.
• textContent → only text (ignores tags).
• innerHTML can render HTML but is riskier (can cause XSS if user input is inserted directly).
• textContent is safer if you only need plain text.

The Document Object Model (DOM) Page 142


Untitled
Wednesday, September 3, 2025 8:48 AM

DOM Attributes Recap


What are Attributes?
• Extra info inside HTML tags (highlighted orange in editors like Atom).
• Examples:
○ class="btn"
○ href="https://google.com"
○ src="image.png"

1. Get Element
document.querySelector("a")
Selects the first <a> element.

2. List Attributes
document.querySelector("a").attributes
✅ Returns a list of attributes for that element.
Example → f=" :// "

3. Get Specific Attribute


document.querySelector("a").getAttribute("href");
// "https://google.com"
N → A b ( )

document.querySelector("a").setAttribute("href", "https://bing.com");
Updates the link’s target, but text stays the same (Google).

Example in Action
<a href="https://google.com">Google</a>
<script>
var link = document.querySelector("a");
console.log(link.getAttribute("href")); // google.com
link.setAttribute("href", "https://bing.com");
</script>
Now clicking Google → B

Key Takeaways
• .attributes → b

The Document Object Model (DOM) Page 143


• .attributes → b
• .getAttribute("name") → b
• .setAttribute("name", "value") → / b
• Works for any HTML element (img, a, input, etc).

The Document Object Model (DOM) Page 144


Untitled
Wednesday, September 3, 2025 8:53 AM

JavaScript: Event Listeners & Loops with Buttons


Goal
• Make buttons respond when clicked.
• Add event listeners to all buttons (not just the first one).

Step 1: Linking JS to HTML


• Place <script src="index.js"></script> just before </body> in index.html.
• Test with:

alert("JS linked!");

B
1. Create a function to handle clicks:

function handleClick() {
alert("I got clicked!");
}
2. Select the first button and add event listener:

document.querySelector("button").addEventListener("click", handleClick);
Why no parentheses?
• handleClick → f f ( )
• handleClick() → y( w w w )

Step 3: Anonymous Function Option


Instead of naming a function, you can pass an anonymous one:

document.querySelector("button").addEventListener("click", function() {
alert("I got clicked!");
});

Step 4: Adding Listeners to All Buttons


Problem: querySelector("button") only selects the first button.
Solution: Use querySelectorAll and a loop.
1. Count how many buttons:

var numberOfDrumButtons = document.querySelectorAll(".drum").length;


2. Use a for loop to add listeners:

for (var i = 0; i < numberOfDrumButtons; i++) {


document.querySelectorAll(".drum")[i].addEventListener("click", function() {
alert("I got clicked!");
});
}

Advanced JS and DOM Manipulation Page 145


}
✅ Now all drum buttons respond with the alert.

Key Concepts Learned


• addEventListener("event", function) attaches a listener.
• Pass the function name (no parentheses) to delay execution.
• Anonymous functions can be used directly.
• querySelectorAll(".class") returns a list →
• Loops (for / while) prevent repeating the same code for multiple elements.

Advanced JS and DOM Manipulation Page 146


Untitled
Wednesday, September 3, 2025 10:33 AM

DevTools quick trick — $0


• In Chrome DevTools: Inspect an element, then type $0 in Console → $0 f
element.
• Useful quick edits:

$0.innerHTML = "AngelaScript"; // temporarily edits the page


• You can attach listeners to $0 directly:

$0.addEventListener("click", function(){ console.log("I got clicked"); });

addEventListener — what it takes & why it looks


weird
• Signature: element.addEventListener(eventTypeString, listenerFunction)
○ First arg: event type (e.g. "click") a string.
○ Second arg: the function to run when the event happens.
• Two common forms:
Named function (pass reference no ()):

function respondToClick() {
console.log("I got clicked!");
}
element.addEventListener("click", respondToClick); // correct called on click

Anonymous function:

element.addEventListener("click", function() {
console.log("I got clicked!");
});
Important: respondToClick ≠ respondToClick()
• respondToClick (no ()) passes the function so the browser calls it later.
• C k() y (y ’ w w )

Passing functions as inputs (Higher-Order Functions)


• JS functions are values you can pass them into other functions and call them inside.
• Calculator example (lecture pattern):

function add(a,b) { return a + b; }


function multiply(a,b) { return a * b; }
function subtract(a,b) { return a - b; }
function divide(a,b) { return a / b; }
function calculator(num1, num2, operator) {
return operator(num1, num2); // operator is a function passed in
}
// usage:
calculator(4,5,add); // 9

Advanced JS and DOM Manipulation Page 147


calculator(4,5,add); // 9
calculator(4,5,multiply); // 20
calculator(6,3,subtract); // 3
calculator(6,3,divide); // 2
• This pattern (functions as inputs) is called a higher-order function and is used all over JS (events,
callbacks, array helpers, etc.).

Debugging with DevTools / debugger


• Insert debugger; in code (or type it in Console) then run the code DevTools will pause execution
at that line.
• While paused you can:
○ Step into (go inside called functions),
○ Step over (run current line),
○ Inspect local variables / call stack.
• Example flow:

debugger;
calculator(3,4,multiply);
• Use step controls to see calculator receive operator as a function and how it calls multiply.

✅ Key takeaways (quick)


• addEventListener needs an event name and a function; pass the function reference (no ()).
• Anonymous vs named listener functions both are valid; named ones are reusable and easier to
debug.
• You can pass functions into functions powerful pattern (HOFs).
• debugger + step controls = best way to see what the browser is actually doing, step-by-step.
• $0 D = y ’ handy for quick tests.

Small challenge (practice)


1. Implement add, multiply, subtract, divide (as above).
2. Implement calculator(num1, num2, operator) that calls operator(num1, num2).
3. Test all combos in Console.
4. Put a debugger; inside calculator and step through a call to see how the operator function is
passed and executed.

Advanced JS and DOM Manipulation Page 148


Untitled
Wednesday, September 3, 2025 11:04 AM

JavaScript Drum Kit – Sounds & Button Identity


Step 1: Playing a Sound with JavaScript
• Create an audio object with new Audio("path").
• Call .play() to play the sound.
Example:

var tom1 = new Audio("sounds/tom-1.mp3");


tom1.play();
This creates an HTMLAudioElement and plays the file.
Commonly found on Stack Overflow / MDN.

Inside event listener:

document.querySelectorAll(".drum")[i].addEventListener("click", function() {
var audio = new Audio("sounds/tom-1.mp3");
audio.play();
});
✅ Now clicking any button plays tom-1.mp3 instead of an alert.

Step 3: Adding Images with CSS


• Assign background images to each button using background-image.
• Example:

.w {
background-image: url("images/tom1.png");
}
.a {
background-image: url("images/tom2.png");
}
.s {
background-image: url("images/tom3.png");
}
.d {
background-image: url("images/tom4.png");
}
.j {
background-image: url("images/snare.png");
}
.k {
background-image: url("images/crash.png");
}
.l {
background-image: url("images/kick.png");
}

Advanced JS and DOM Manipulation Page 149


}
Each button now looks like the drum it represents.

Step 4: Identify Which Button Was Clicked


• Inside the event listener, this refers to the element that triggered the event.
• Example:

document.querySelectorAll(".drum")[i].addEventListener("click", function() {
console.log(this.innerHTML); // shows button text
});
this.innerHTML tells us which drum button was clicked.

Challenge: Change Style of Clicked Button


this.style.color = "white";

✅ Clicking a button changes its text color to white.

Key Concepts Learned


• new Audio("file").play() plays a sound.
• Each button can have a different background via CSS.
• this keyword = identity of the element that fired the event.
• You can use this.innerHTML to figure out which button was pressed.
• You can modify styles dynamically (e.g., this.style.color).

Advanced JS and DOM Manipulation Page 150


Untitled
Wednesday, September 3, 2025 11:19 AM

JavaScript Drum Kit: Switch Statement


W at’ a ?
• We want different drum sounds to play depending on which button is clicked.
• Using if-else for 7 buttons = messy and repetitive.
• Solution: Use a switch statement, which is like a railroad switch it sends code down
different tracks based on the value of a variable.

Setting Up the Switch Statement


1. Start typing switch in Atom → autosuggest gives skeleton code. ✨
2. Syntax:

switch(expression) {
case 'value':
// code to execute
break;
default:
// code if no case matches
}
3. Our plan: Switch on buttonInnerHTML → b k

Step 1: Capture Button Letter


• Create a variable:

let buttonInnerHTML = this.innerHTML;


• This is the bu on that triggered the event.

Step 2: Define Cases


1. ‘ ’ -1 drum

case 'w':
tom1.play();
break;
2. ‘ ’ -2 drum

case 'a':
tom2.play();
break;
3. Repeat for: s, d, j, k, l → y ff
4. Important: Always end each case with break → f “f ”⛔

Step 3: Default Case


• Like an else for switch. ❗
• Covers unexpected input: e.g., clicking 1 or , instead of a valid button.
• Good practice to always include it:

default:
console.log(buttonInnerHTML);

Advanced JS and DOM Manipulation Page 151


console.log(buttonInnerHTML);
• Ensures your code is robust and error-resistant.

Step 4: Naming Audio Variables


• Instead of generic audio, give meaningful names:
○ tom1, tom2, etc., matching the sound file.
• Consistency = easier to debug and maintain.

Step 5: Test It
1. Save → f w b
2. Click bu ons → d t d lay a
3. ext step: keyboard events → y ad f k

Key Takeaways:
1. Switch statement = cleaner than multiple if-else ✅
2. Use meaningful variable names →
3. Break after each case → b ⛔
4. Include a default case → x
5. Test your code → k y w k x

Pro Tip: Think of switch as a decision tree. Each case is a branch, and the default is the safety net at
the bottom.

Advanced JS and DOM Manipulation Page 152


Untitled
Wednesday, September 3, 2025 11:21 AM

JavaScript Objects & Constructor Functions


W at’ a j t?
• Think of objects as structured containers for data like employees in a hotel.
• Instead of creating multiple loose variables, objects group related data together.

Step 1: Objects in Real Life


• Scenario: You inherit a hotel.
• Problem: Many bellboys, guests, and luggage.
• Solution: Assign a bellboy, Timmy, with properties like:
○ Name → y
○ Age → 19
○ Work permit →
○ Languages → [ ,S ]
• Access data: bellBoy1.name → " y" ✅
• Lesson: Objects = clean, structured, less error-prone than multiple variables.

Step 2: Creating an Object


• Syntax:

var bellBoy1 = {
name: "Timmy",
age: 19,
hasWorkPermit: true,
languages: ["English", "Spanish"]
};
• Access properties using dot notation:

console.log(bellBoy1.name); // Timmy
• Tip: Different objects have different properties (bellboy vs. housekeeper).

Step 3: Housekeeper Example


• Create an object for a housekeeper:
○ name → "J "
○ yearsOfExperience → 12
○ cleaningRepertoire → ["b ", " bby", "b "]
• Access example: houseKeeper1.cleaningRepertoire ✅

⚡ Step 4: Scaling with Constructor Functions


• Problem: Multiple bellboys → w bj y=
• Solution: Factory / Constructor Function → y w bj w
properties.

Step 5: Constructor Function Syntax


• Naming: Capitalized first letter (e.g., BellBoy)
• Structure:

Advanced JS and DOM Manipulation Page 153


• Structure:

function BellBoy(name, age, hasWorkPermit, languages) {


this.name = name;
this.age = age;
this.hasWorkPermit = hasWorkPermit;
this.languages = languages;
}
• Create new objects:

var bellBoy1 = new BellBoy("Timmy", 19, true, ["English", "Spanish"]);


var bellBoy2 = new BellBoy("Jimmy", 22, true, ["English"]);
• Keyword new → f bj f

Step 6: Housekeeper Constructor


• Example:

function HouseKeeper(yearsOfExperience, name, cleaningRepertoire) {


this.yearsOfExperience = yearsOfExperience;
this.name = name;
this.cleaningRepertoire = cleaningRepertoire;
}

var houseKeeper1 = new HouseKeeper(9, "Tom", ["lobby", "bedrooms"]);


console.log(houseKeeper1.name); // Tom
• Benefit: Easy to create multiple objects with the same structure.
• Lesson: Constructor functions = object factories for consistent, scalable data.

Key Takeaways
1. Objects group related properties and methods into one structure ✅
2. Use dot notation to access object properties: object.property
3. Constructor functions help create multiple similar objects efficiently
4. Capitalized function name + new keyword` = signals object creation.
5. Objects = cleaner, scalable, and less error-prone than standalone variables.

Pro Tip:
Think of objects like blueprints for employees.
• BellBoy blueprint → , , ,
• HouseKeeper blueprint → , x , k
• Factory = constructor → y w ff w b ✨

Advanced JS and DOM Manipulation Page 154


Untitled
Wednesday, September 3, 2025 11:23 AM

JavaScript Objects: Methods


W at’ a t d?
• A method is a function that belongs to an object.
• Similar to properties, but callable with parentheses ().

Step 1: Adding Methods to an Object


• Example: BellBoy object can move a suitcase.

bellBoy1.moveSuitcase = function() {
alert("May I take your suitcase?");
// code to move suitcase
};
• Call the method:

bellBoy1.moveSuitcase();
• Remember: Dot notation works for both properties and methods. ✅

Step 2: Methods in Constructor Functions


• Include methods directly inside constructor functions:

function BellBoy(name, age, hasWorkPermit, languages) {


this.name = name;
this.age = age;
this.hasWorkPermit = hasWorkPermit;
this.languages = languages;
this.moveSuitcase = function() {
alert("May I take your suitcase?");
};
}
• Every new object created from this constructor automatically inherits the method.

Step 3: HouseKeeper Method Example


• Add a clean method to the HouseKeeper constructor:

function HouseKeeper(yearsOfExperience, name, cleaningRepertoire) {


this.yearsOfExperience = yearsOfExperience;
this.name = name;
this.cleaningRepertoire = cleaningRepertoire;
this.clean = function() {
alert("Cleaning in progress...");
};
}
• Create object:

var houseKeeper1 = new HouseKeeper(12, "James", ["bedrooms"]);


houseKeeper1.clean(); // Alerts: "Cleaning in progress..."
• Lesson: Methods = object-specific behaviors that can act on properties or perform tasks.

Advanced JS and DOM Manipulation Page 155


• Lesson: Methods = object-specific behaviors that can act on properties or perform tasks.

Step 4: Real-World Analogy: Audio Objects


• Audio objects (new Audio("file.mp3")) also have:
○ Properties → ,f
○ Methods → , y()
• Y ’ ,b y ’ creating your own objects
with methods.

Step 5: Key Takeaways


1. Methods = functions inside objects ✅
2. Access methods with dot notation + parentheses: object.method()
3. Add methods in constructor functions → all objects from the factory inherit them
4. Objects combine properties + methods → f f -world entities
5. Practice → f y w =

Pro Tip:
Think of an object as a person:
• Properties = traits (name, age, experience)
• Methods = actions they can perform (moveSuitcase, clean, play sound)
• Dot notation = w y “ k ” k ✨

Advanced JS and DOM Manipulation Page 156


Untitled
Wednesday, September 3, 2025 11:24 AM

Java t: D t y ad y
Goal:
• Make your drum kit respond to keyboard keys as well as button clicks.
• Example: Press w → -1 ,P j→

Step 1: Keypress Event Listener


• Instead of listening for clicks, listen for key presses:

document.addEventListener("keypress", function(event) {
alert("Key was pressed");
});
• Tip: Event names are all lowercase (keypress). Check MDN docs for accurate names.
• Key idea: Add the listener to the entire document, not a specific button.

Step 2: Detect Which Key Was Pressed


• Pass a parameter (e.g., event or e) to your event listener:

document.addEventListener("keypress", function(event) {
console.log(event);
});
• Logs keyboard event object → :
○ key → k y
○ keyCode → fk y
○ other properties
• Most important: event.key → f k y ✅

Step 3: Reuse Existing Switch Logic


• Previously: switch statement checked buttonInnerHTML for button clicks.
• New approach: create a function that takes a key and plays the correct sound:

function makeSound(key) {
switch(key) {
case 'w':
tom1.play();
break;
case 'a':
tom2.play();
break;
// ... other cases
}
}
• Call makeSound() from both button click and keyboard keypress.

Step 4: Button Clicks


• For buttons:

Advanced JS and DOM Manipulation Page 157


button.addEventListener("click", function() {
makeSound(this.innerHTML);
});
• Sends the innerHTML of the button to makeSound().

⌨ Step 5: Keyboard Presses


• For keyboard:

document.addEventListener("keypress", function(event) {
makeSound(event.key);
});
• Sends the key value of the pressed keyboard key to makeSound().

Step 6: Unified Logic


• makeSound(key) handles all sound logic, regardless of source:
○ Button click → H ML
○ Keyboard press → k y
• Result: One place for all sound handling → , b ✅

Key Takeaways
1. Event listeners can be added to elements or the entire document.
2. y a d v t give a lot of info, but event.key is usually all you need.
3. Functions as parameters: Pass makeSound to event listeners →
4. Unified function =D Y (D ’ Y f)
5. JavaScript callbacks → after events happen.

Pro Tip:
Think of it like a translator:
• B k yb k y k ff “ ”→ k S () b
same action: play a drum.

Advanced JS and DOM Manipulation Page 158


Untitled
Wednesday, September 3, 2025 11:26 AM

Drum Kit: Button Animation


Goal: Make buttons flash when pressed (click or keyboard) so the user knows the key worked.

Step 1: Create a Button Animation Function


• Function handles animation for both button clicks and keyboard presses.
• Example:

function buttonAnimation(currentKey) {
var activeButton = document.querySelector("." + currentKey);
activeButton.classList.add("pressed");
}
• Parameter: currentKey → f b k y

Step 2: Call Animation on Button Click


button.addEventListener("click", function() {
makeSound(this.innerHTML);
buttonAnimation(this.innerHTML);
});
• Adds visual feedback when a drum button is clicked.

⌨ Step 3: Call Animation on Key Press


document.addEventListener("keypress", function(event) {
makeSound(event.key);
buttonAnimation(event.key);
});
• Pressing a keyboard key triggers the same animation and sound as clicking the button.

Step 4: Query the Correct Button


• Buttons in HTML have:
○ class drum
○ additional class for the key (w, a, s, etc.)
• Use querySelector to select the button for animation:

document.querySelector("." + currentKey);
• Dot + key → CSS f ( w, k)

✨ Step 5: Apply Pressed Class


• CSS class pressed → w+ y ff
• Add class:

activeButton.classList.add("pressed");

⏱ Step 6: Remove Pressed Class After Delay


Advanced JS and DOM Manipulation Page 159
⏱ Step 6: Remove Pressed Class After Delay
• Want the animation to revert → f ff
• Use setTimeout to remove the class:

setTimeout(function() {
activeButton.classList.remove("pressed");
}, 100); // 0.1 second delay
• Result → b f b f y, y

Step 7: Unified Animation Logic


• Function buttonAnimation(currentKey) works for:
1. Button clicks → H ML
2. Keyboard presses → k y
• Ensures consistent UX feedback for all input methods.

Key Takeaways
1. Use querySelector + dynamic class to select the right element. ⌨
2. Use classList.add() to apply CSS animations. ✨
3. Use setTimeout() to revert animation → f ff ⏱
4. One function handles both button clicks and keyboard presses → D Y ✅
5. Combines JavaScript events + DOM manipulation + CSS for interactive UX.

Pro Tip:
Think of it like a real drum kit:
• You press a key or hit a pad → lights up and makes sound.
• Same feedback for all inputs keeps the user confident they pressed the right key.

Advanced JS and DOM Manipulation Page 160


Untitled
Wednesday, September 3, 2025 11:27 AM

Introduction to jQuery
What is jQuery?
• jQuery is the most popular JavaScript library.
• A library = pre-written code you can use to simplify your own projects.
• Created by John Resig to make JavaScript easier, shorter, and more readable.

Problem jQuery Solves


• In pure JavaScript, even simple tasks can be long and repetitive:
○ Example:
▪ Query all buttons in the DOM.
▪ Add a click event listener to each button.
▪ Change the style of an h1 element.
▪ Use a for-loop to traverse all buttons.
• Frustration: Too many lines for something simple → “j f y ”!

How jQuery Helps


1. Simplifies DOM selection:
○ Vanilla JS:

document.querySelector("h1");
○ jQuery:

jQuery("h1"); // or shorthand: $("h1")

✅ Same result, much shorter and readable.


2. Simplifies event handling:
○ Vanilla JS: multiple lines to loop and attach events.
○ jQuery handles it in one line.
3. Easier to debug and maintain:
○ Less code → f w k
○ Faster to write, easier to read.

Key Takeaways
• jQuery = a tool to reduce JavaScript complexity.
• Use $() shorthand for querying elements.
• Makes DOM manipulation, event handling, and animations simpler.
• Think of it like shortcuts in UX design: achieves the same functionality with less effort.

UX Perspective:
• jQuery improves developer efficiency → f f user experience.
• Less verbose code = faster iteration → b ,f X

JQuery Page 161


Untitled
Wednesday, September 3, 2025 11:40 AM

Incorporating jQuery into Your Website

jQ y
• Download directly from jquery.com or use a CDN (Content Delivery Network).
• Recommended: Google CDN → b w b y f →f
load.
• Latest version (as of lesson): 3.3.1 (could be newer).

j t t
• Create project folder → jQ y
• Create files:
1. index.html
2. styles.css
3. index.js
• Link CSS in <head>:

<link rel="stylesheet" href="styles.css">


• Link JS at end of body:

<script src="index.js"></script>
✅ Including JS at the end ensures HTML elements exist before manipulation.

T a L
• Change body background color in CSS → f w k
• Add test JS alert:

alert("Working");
• Refresh browser → k CSS

Add TML l t
• Example:

<h1>Hello</h1>
<button>Click Me</button>
<button>Click Me</button>
<button>Click Me</button>
<button>Click Me</button>
<button>Click Me</button>

a jQ y y ta
• $→ f jQ y
• Example: change h1 color to red:

$("h1").css("color", "red");
• Equivalent:

JQuery Page 162


• Equivalent:

jQuery("h1").css("color", "red");

I l d jQ yL ay
• Copy script tag from Google Hosted Libraries.
• Place above your JS script tag in HTML:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="index.js"></script>
• ❌ Wrong order → $ f
• ⚠ Avoid putting both scripts in <head> without ready() → y y b f
library is loaded.

D t ady M t d
• Ensures jQuery code runs after page is fully loaded:

$(document).ready(function() {
$("h1").css("color", "red");
});
• Alternative → at end of body → ff , y()

y Ta a ay
1. $ = jQuery shorthand → ,
2. Script order matters → jQ y b y before your JS.
3. Document ready → f b f DOM
4. Use jQuery to select elements and manipulate CSS easily.

Pro Tip:
Including scripts at the end of body is often simpler than using $(document).ready() → DOM
elements exist when JS runs.

JQuery Page 163


Untitled
Wednesday, September 3, 2025 11:41 AM

Understanding Minified jQuery (and JS/CSS Files)

W at aM dL a y?
• Minified files look like a “huge mess” when opened in a browser.
• Example: jQuery from a CDN appears as one long line of code.
• Purpose: Reduce file size for faster loading in browsers.

W at a D M a
• Removes:
○ Spaces
○ New lines
○ Comments
• Keeps all functional code intact.
• Makes file smaller → f w f

a l
• Original index.js for drumkit: 1539 bytes
• Minified version: 1113 bytes → 426 bytes saved
Effect: Less bandwidth, quicker load times, same functionality.

t M yY C d
• Use minifier.org
1. Paste your JS or CSS code.
2. Select language (JS or CSS).
3. Click Minify →

W yM a Ma
• Browsers ignore whitespace, tabs, and comments → y yf x
• Minification improves performance, especially for slower connections.
• Standard practice for production websites.

a ada l v M d
• Libraries usually provide both:
1. Readable version → f / z
2. Minified version → f /b w
• If no customization needed → y f f f CDN w

Key Tip:
Always use minified files in production to improve website speed, but keep the readable version for
development and debugging.

JQuery Page 164


Untitled
Wednesday, September 3, 2025 11:42 AM

Selecting Elements in jQuery

W y l I ta t
• To manipulate elements, you first need to select them.
• Standard JavaScript uses:

document.querySelector("h1");
document.querySelectorAll("button");

jQ y l
• $ is shorthand for jQuery.
• Selecting elements becomes shorter and cleaner:

$("h1"); // Selects the first h1


$("button"); // Selects all buttons
• Works similarly to CSS selectors.

C l t C a l ty
• You can use any CSS selector inside $():

$("h1.title"); // h1 element with class "title"


$("#header h1"); // h1 inside div with id "header"
$(".container p"); // All p inside elements with class "container"

l M l l l t
• Unlike querySelector vs querySelectorAll in JS, $() handles both single and multiple elements
seamlessly:

$("button"); // Returns all buttons as a jQuery object

Key Tip:
Using $() makes your code more concise, flexible, and CSS-like, which is one reason jQuery became
popular.

JQuery Page 165


Untitled
Wednesday, September 3, 2025 11:43 AM

Manipulating Styles in jQuery

T () M t d
• Purpose: Change or get CSS properties of selected elements.
• Syntax:

$("selector").css("property"); // Get the value


$("selector").css("property", "value"); // Set the value
• Example:

$("h1").css("color", "green"); // Changes h1 text color to green


console.log($("h1").css("font-size")); // Gets current font size, e.g., "32px"
• Notes:
○ One argument → get the value
○ Two arguments → set the value
○ Directly setting styles is okay for quick tweaks but mixes behavior with appearance, which
is not ideal.

Cla I t ad D t tyl
• Better Practice: Keep CSS in the stylesheet; keep behavior in JS.
• Steps:
1. Define a CSS class in styles.css:

.big-title {
font-size: 10rem;
color: yellow;
font-family: cursive;
}
2. Use jQuery to add/remove the class:

$("h1").addClass("big-title"); // Adds the class


$("h1").removeClass("big-title"); // Removes the class

Add M l l Cla
• Separate class names with a space inside .addClass():

$("h1").addClass("big-title margin-50");
• Example CSS:

.margin-50 {
margin: 50px;
}
• Both classes will be applied simultaneously.

C a l t a a Cla
• Method: .hasClass()

JQuery Page 166


• Method: .hasClass()
• Returns true or false

$("h1").hasClass("margin-50"); // true or false

Key Tips:
• Using classes keeps behavior (JS) and styles (CSS) separate cleaner and more maintainable.
• .css() is useful for dynamic or one-off style changes.
• .addClass(), .removeClass(), and .hasClass() are essential for interactive styling

JQuery Page 167


Untitled
Wednesday, September 3, 2025 11:44 AM

Manipulating Attributes with jQuery

T a () M t d
• Purpose: Get or set the value of an HTML attribute.
• Syntax:

$(selector).attr("attribute"); // Get the value


$(selector).attr("attribute", "value"); // Set the value

a A t
• Example: Getting the src of an image:

console.log($("img").attr("src"));
○ Prints the current src value of the image element(s).

a A t
• Example: Changing the href of an anchor tag:

$("a").attr("href", "https://www.yahoo.com");
○ Updates all anchor tags to point to Yahoo instead of Google.
• If you check after running:

console.log($("a").attr("href")); // "https://www.yahoo.com"

Cla A A t T
• The class attribute can also be read or changed with .attr():

console.log($("h1").attr("class")); // "big-title margin-50"


• This prints all classes applied to the selected element.

Key Notes:
• One argument → get the attribute value
• Two arguments → set the attribute value
• Works with all HTML attributes: src, href, alt, title, class, etc.
• Useful for dynamically updating links, images, or any element property.

JQuery Page 168


Untitled
Wednesday, September 3, 2025 11:45 AM

Adding Event Listeners with jQuery

T l () M t d
• Adds a click event listener to one or more elements.
• Syntax:

$("selector").click(function() {
// code to execute when clicked
});
• Example: Change an h1 color on click:

$("h1").click(function() {
$(this).css("color", "purple");
});
• Bonus: jQuery automatically applies the listener to all matching elements, no need for loops.

t v tM t d
• Similar to .click(), jQuery has other shorthand methods like:
○ .keypress() → k y k
○ .mouseover() →
○ .keydown() / .keyup() → f k y

D t yt
• Detecting keystrokes inside an input:

$("input").keypress(function(event) {
console.log(event.key); // logs which key was pressed
});
• Detecting keystrokes on the entire page:

$(document).keypress(function(event) {
$("h1").text(event.key); // show the key in the h1
});

T () M t d
• More flexible than .click() or .keypress().
• Syntax:

$("selector").on("event", function() {
// code to execute
});
• Example: Detect mouseover on an h1:

$("h1").on("mouseover", function() {
$(this).css("color", "purple");
});

JQuery Page 169


});
• Can listen for any DOM event, including click, keypress, mouseover, mouseout, etc.

✅ Key Points
• jQuery simplifies event handling, no loops needed for multiple elements.
• .on() is versatile and often preferred for dynamic content.
• Event object (event) gives access to properties like event.key.
• Use .text() to update the text of elements dynamically.

JQuery Page 170


Untitled
Wednesday, September 3, 2025 11:47 AM

Adding New Elements with jQuery


jQuery allows you to create and insert HTML elements on the fly without touching your original HTML
file.

()
• Adds content before the selected element (outside of it).
• Example:

$("h1").before("<button>New</button>");
○ Adds a button before the <h1> element.

a ()
• Adds content after the selected element (outside of it).
• Example:

$("h1").after("<button>New</button>");
○ Adds a button after the <h1> element.

d()
• Adds content inside the selected element, at the start (right after the opening tag).
• Example:

$("h1").prepend("<button>New</button>");
○ The button appears before the text content of the <h1>.

a d()
• Adds content inside the selected element, at the end (right before the closing tag).
• Example:

$("h1").append("<button>New</button>");
○ The button appears after the text content of the <h1> but still inside the <h1>.

Removing Elements
• Use .remove() to delete elements from the DOM.
• Example:

$("button").remove(); // Removes all buttons on the page


• Works on any selector: IDs, classes, tags, etc.

Key Notes:
• before() and after() → outside the element.
• prepend() and append() → inside the element.
• These methods give you precise control over where new elements appear.
• .remove() is simple but powerful for dynamic cleanup.

JQuery Page 171


Untitled
Wednesday, September 3, 2025 11:48 AM

Basic jQuery Animation Methods


/ d /T l
• .hide() → H ( f f w)
• .show() → S w
• .toggle() → Sw b w w

$("button").click(function() {
$("h1").toggle();
});

ad A a
• Gradual change in opacity:
○ .fadeOut() → S w y
○ .fadeIn() → S w y w
○ .fadeToggle() → f /f O

$("button").click(function() {
$("h1").fadeToggle();
});

ld A a
• Vertical slide effects:
○ .slideUp() → C w
○ .slideDown() → x w w
○ .slideToggle() → b w / D w

$("button").click(function() {
$("h1").slideToggle();
});

C t A a t a at ()
• Allows numeric CSS properties to gradually change:
○ Can animate opacity, margin, height, width, etc.
○ Cannot animate colors or non-numeric values.

$("button").click(function() {
$("h1").animate({
opacity: 0.5,
marginLeft: "20px"
});
});

C a A a
• Apply multiple effects in order by chaining methods:

JQuery Page 172


$("h1").slideUp().slideDown().animate({opacity: 0.5});
• jQuery executes each animation sequentially, not simultaneously.

Key Tips
• Animations like .fadeIn(), .slideDown(), .animate() make the UI feel more dynamic.
• Only numeric CSS values can be used in .animate().
• Use chaining to combine multiple animations in sequence.
• D ’t t d a know what exists and how to find them via:
○ jQuery documentation
○ Google searches or Stack Overflow

JQuery Page 173


Untitled
Wednesday, September 3, 2025 11:49 AM

Introduction to the Command Line


W at a ll?
• Shell: Interface that lets you interact with the kernel (core of your operating system).
• Types of Shells:
1. Graphical User Interface (GUI): Example – Finder (Mac), Explorer (Windows)
2. Command Line Interface (CLI): Text-based interface to issue commands directly to the OS.

a ll
• Bash: Bourne Again Shell, a popular CLI for Unix-like systems.
• Unix-like systems examples:
○ Linux distributions
○ Mac OS / macOS
• Windows equivalent: DOS / PowerShell
• Why use Bash?
○ Speed: Quickly execute commands like creating folders, moving files, etc.
○ Control: Access hidden files, configuration, and advanced system settings.
○ Flexibility: Full control over operations without the GUI constraints.

a a C a d
• Create directory: mkdir Music → M k wf
• List all files (including hidden): ls -a
• Create hidden folder: mkdir .Secrets
Tip: Press the up arrow to repeat previous commands saves time!

W yL a CLI?
• GUI hides many details; CLI gives you full visibility of the system.
• Essential for Web Development, Back-end Development, and Version Control (Git).
• Many developers prefer CLI for speed and control over tasks.

a al t
• Faster folder creation and navigation.
• Access hidden or system files easily.
• Crucial for advanced developer tasks like Git, server management, and automation scripts.

Summary:
The Bash shell is a powerful tool for developers. It provides speed, precision, and control that GUI
interfaces often hide. Learning Bash early makes you a more efficient and capable developer.

Unix Command Line Page 174


Untitled
Wednesday, September 3, 2025 11:52 AM

Getting Started with the Terminal


t T al
• Terminal appearance may differ depending on preferences.
○ Example: green text on black background for better night-time visibility.
• Fun tip: hackertyper.com lets you “pretend” to write code like a hacker.

Basic Navigation Commands


L l
• Command: ls → L y
• Current location: indicated by ~ (tilde) = user root directory.

C a D t
• Command: cd <folder> → C y f
○ Example: cd Documents → D f
• Tab auto-completion: Start typing a folder name and press Tab to auto-complete.
• Navigating multiple levels:

cd Documents/Learn/Languages
○ Moves through the full path in one command.

a ad
• Parent directory: cd .. → G
• Chain to go multiple levels up:

cd ../.. # Up two levels

Q Nav a T
• Return to user root: cd ~
• Cycle previous commands: use up ↑ and down ↓ keys.
• Edit anywhere in a command line: hold Option/Alt and click to move the cursor.
• Move cursor to start/end:
○ Ctrl + A → b f
○ Ctrl + E → f
• Clear current line without executing:
○ Ctrl + U →

W y T T
• Efficient keyboard navigation saves time over using a mouse.
• Useful for:
○ Navigating deeply nested directories.
○ Executing long commands quickly.
○ Avoiding repetitive typing with auto-completion and history.

Unix Command Line Page 175


Summary:
Mastering ls, cd, and keyboard shortcuts allows you to move through directories efficiently, manipulate
paths quickly, and stay productive without touching the mouse.

Unix Command Line Page 176


Untitled
Wednesday, September 3, 2025 11:53 AM

Directory Creation and Navigation


C a aD t y
• Command: mkdir <directory_name> → M k w y
○ Example:

mkdir Angela
• Navigate into the directory: cd Angela
• Check contents: ls → b y y

a al I t a v C a dL
• GUI: Open an editor like TextEdit → f → y
• Command Line: touch <filename> → wf y
○ Example:

touch Text2.txt
l
• Default app:

open Text2.txt
• Specify application:

open -a TextEdit Text2.txt

Deleting Files
v a l l
• Command: rm <filename>

rm Text.rtf
v All l aD t y
• Wildcard *: matches all files.

rm *
I ta t Ca
• Always check your location before using destructive commands (rm) with pwd or ls.
• C ’ y k G

Removing Directories
v ty D t y
• Command:

Unix Command Line Page 177


rmdir <directory_name>
○ Only works if directory is empty.
v D t y t C t t
• Command: rm -r <directory_name> → -r = recursive.
○ Example:

rm -r Angela
• Removes directory and all child files/folders.
Da C a d Wa
• sudo rm -rf / --no-preserve-root → w y ( +f + )
• Moral: with great power comes great responsibility. Always double-check your path and target.

Key Notes
• Check current location: pwd → f
• List files/folders: ls → w
• Wildcard *: selects everything inside current directory.
• Command line provides power and efficiency, but mistakes can be destructive.

Summary:
Command-line file and directory manipulation is faster, more precise, and scriptable. Use mkdir, touch,
rm, and rm -r carefully. Always check your path before destructive commands.

Unix Command Line Page 178


Untitled
Wednesday, September 3, 2025 11:57 AM

Git & Version Control


What is Git?
• Git = version control system for your code.
• Lets you track, save, and restore versions of your projects.
• Think of it as a time machine for your code ⏳

Step 1: Version Control Basics


• Create a new le → w
• Save point 1 → Version 1
• Add more code → 2 → Version 2
• Accidentally break code → G y roll back to a previous version

Step 2: Compare & Restore


• Compare your current code vs. previous versions → see changes
• Roll back to any save point → restore old code
• Flexibility: jump back or forward in version history

⚡ Step 3: Why Git is Powerful


• Protects against irreversible mistakes
• Handles interlinked code and dependencies efficiently
• Supports teamwork → w k w f

Step 4: Next Steps


• Next lesson: hands-on Git on the command line
• Learn how to:
○ Clone repositories
○ Fork projects
○ Make Pull Requests
○ Merge code
• Goal: gain confidence in managing code versions

Key Takeaways
1. Git = time machine for your code ⏳
2. Version control = save points you can revert to
3. Compare versions → see what changed
4. Roll back anytime → recover from mistakes
5. Git = teamwork tool → easier collaboration

Pro Tip:

Git^JGitHub and Verson Control Page 179


Pro Tip:
Think of Git as a “ t y t ” avd a :
• Save often
• Experiment freely
• If things go wrong → load the last checkpoint ✨

Git^JGitHub and Verson Control Page 180


Untitled
Wednesday, September 3, 2025 11:58 AM

Git: Local Repository & Version Control


Goal: Learn how to track and manage changes locally on your computer using Git.

Step 1: Setting Up
• Open Terminal → D k :

cd Desktop
• Create a project folder called Story:

mkdir Story
cd Story
• Check contents → b y:

ls
• Create a text file → 1 x:

touch chapter1.txt
• Open and edit le → y

⚡ Step 2: Initialize Git


• Start version control:

git init
• Creates .git folder (hidden) → G
• Working directory = your project folder (Story)

Step 3: Staging & Committing


• Staging area = intermediate step where you decide which files to commit.
• Check status:

git status
○ Red = untracked (not staged)
○ Green = staged (ready to commit)
• Add file to staging:

git add chapter1.txt


• Commit changes → G :

git commit -m "Complete chapter 1"


• Use present tense in commit messages → b

Step 4: Multiple Files


• Create more files → 2 x, 3 x
• Edit files → :

git add chapter2.txt chapter3.txt

Git^JGitHub and Verson Control Page 181


git add chapter2.txt chapter3.txt
• Or add all files in folder:

git add .
• Commit changes:

git commit -m "Complete chapter 2 and 3"


• View commit history:

git log
○ Shows unique hash, author, timestamp, and commit message
• HEAD = points to current position/version in repository

Step 5: Reverting Changes


• Accidentally mess up a file? Don’t worry!
• Check modified files:

git status
• See differences between last commit and current file:

git diff chapter3.txt


○ Red = deleted
○ Green = added/changed
• Revert file to last committed version:

git checkout chapter3.txt


○ Restores file to last saved state

Key Concepts Recap


1. Working directory → y j f
2. Staging area → z b f
3. Local repository →
4. Commit → w & q
5. git diff → w
6. git checkout →

Pro Tip:
• Staging area lets you pick which files to track → w f b
committed.
• Commit often → , b
• HEAD always shows your current version checkpoint

Git^JGitHub and Verson Control Page 182


Untitled
Wednesday, September 3, 2025 12:00 PM

Git: Remote Repository on GitHub


Goal: Push your local repository to GitHub and track commits online.

Step 1: Set up GitHub Account


• Go to github.com → S (F )
• Confirm email → S

Step 2: Create Remote Repository


• Click +
• Name: Story
• Description: "My masterpiece"
• Visibility:
○ Public → y
○ Private → yy + b
• Do not initialize README yet
• Click Create repository ✅

⚡ Step 3: Link Local Repo to Remote


• Copy repository URL from GitHub
• In terminal, inside local Story directory:

git remote add origin <repository-URL>


○ origin = default remote name (convention)

Step 4: Push Local Commits to Remote


• Push to GitHub:

git push -u origin main


○ -u → k b b
○ origin →
○ main → b ( f )
• Refresh GitHub → f

Git & GitHub Concept Recap


1. Working Directory → f w f
2. Staging Area → w f
3. Local Repository → y
4. Commit → w q &
5. Main Branch → q f
6. Remote Repository → b k (G H b)
7. git push → y

Tips & Notes


• Main branch = main timeline of project
• Remote repository = optional but essential for collaboration & backup

Git^JGitHub and Verson Control Page 183


• Remote repository = optional but essential for collaboration & backup
• You can check differences between local and remote before pushing
• Refresh GitHub → , ,

Git^JGitHub and Verson Control Page 184


Untitled
Wednesday, September 3, 2025 12:01 PM

Git Ignore Files (.gitignore)


Goal: Prevent certain files from being committed to local and remote Git repositories (e.g., secrets,
system files).

Why Use .gitignore?


• Protect sensitive data: API keys, passwords (secrets.txt)
• Avoid system/user files: e.g., .DS_Store (Mac), Thumbs.db (Windows)
• Prevent unnecessary clutter in remote repositories

Step 1: Create a Project


cd ~/Desktop
mkdir Project
cd Project
touch file1.txt file2.txt file3.txt secrets.txt
• Files created: file1.txt, file2.txt, file3.txt, secrets.txt

Step 2: Create .gitignore


touch .gitignore
• Important: name and case matter →
• Hidden file → kw -a
• Open in VS Code and add files to ignore:

# User/system files
.DS_Store
# Sensitive data
secrets.txt
• You can also use wildcards:

*.txt # ignore all .txt files

Step 3: Initialize Git and Stage Files


git init # initialize repository
git add . # stage files
git status # check staged files
• Undo staging if needed:

git rm --cached -r .

Step 4: Commit
git add .
git status # only files not ignored are staged

Git^JGitHub and Verson Control Page 185


git status # only files not ignored are staged
git commit -m "Initial commit"
• Only files not listed in .gitignore are committed

Step 5: Node Projects (.gitignore template)


• Node projects have common files to ignore: node_modules/, .env, etc.
• GitHub provides a collection of gitignore templates:
GitHub gitignore repo
• Copy Node template into .gitignore:

# Node dependencies
node_modules/
# Environment variables
.env
# System files
.DS_Store
• Initialize & commit as usual:

git init
git add .
git commit -m "Initial commit"

Tips
• Always include API keys & secrets in .gitignore
• Use comments (#) to organize ignored files
• .gitignore works locally → y w G H b

Git^JGitHub and Verson Control Page 186


Untitled
Wednesday, September 3, 2025 12:04 PM

GitHub: Cloning a Remote Repository


What is Cloning?
• Cloning = pulling a remote repository from GitHub to your local machine.
• Command:

git clone <repository-url>


• Purpose:
○ Make a local copy of someone else’s project. ✅
○ Continue development on your own branch.
○ Fix bugs, customize features, or extend functionality.

W y Cl l ’ j t?
1. Customize it for your needs.
2. Extend functionality the original project doesn’t have. ⚡
3. Fix bugs.
4. Learn by studying someone else’s code.
• Example: self-hosted apps as alternatives to paid services (e.g., project management tools, email
servers).

1. Copy repository URL from GitHub.


2. Run in terminal:

git clone <URL>


3. cd into the repository:

cd repository-name
4. Install dependencies (if Node.js project):

npm install

Step 2: Run Cloned Projects


Example 1: QuakeJS
• Retro Quake game built in JavaScript.
• Steps:
1. Clone repo
2. Install npm packages
3. Set content server: content.quakejs.com
4. Run server with Node → b 8080
• Result: Play Quake in browser using cloned code.
Example 2: Word Mastermind (Wordle clone)
• JavaScript, HTML, CSS game.
• Steps:
1. Clone repo
2. cd word-mastermind
3. npm install

Git^JGitHub and Verson Control Page 187


3. npm install
4. npm start → b w
• Benefits:
○ Play multiple words per day
○ Modify code, change colors, or update game logic

Step 3: Learning from Open Source


• ’ :
○ Understand structure & logic.
○ Improve your skills by modifying small parts initially, more later. ✨
• Explore folders like dict (Wordle) or src to see the actual code.

Step 4: Contributing to Open Source


• Once comfortable:
○ Make a Pull Request
○ Work on Branches
○ Learn Merging
• Start with beginner-friendly repos:
○ awesome-for-beginners GitHub list
○ Examples: AncientBeast (turn-based strategy), Brave Browser (crypto rewards)

Key Takeaways
1. Cloning = local copy of remote repository ✅
2. Use git clone <URL> + npm install + npm start to run projects locally
3. Modify & experiment to improve programming skills ✨
4. Open source = learning + contribution opportunity
5. Future skill: Branches, Pull Requests, Merging for collaboration

Pro Tip:
• Think of cloning like standing on the shoulders of giants ’w k f
and create more efficiently.

Git^JGitHub and Verson Control Page 188


Untitled
Wednesday, September 3, 2025 12:05 PM

Git: Branches & Branching


What is a Branch?
• A branch is a parallel version of your repository where you can try new ideas without affecting
the main project.
• Useful for:
○ Building new features
○ Experimenting with code
○ Fixing bugs without breaking main branch ⚡

Step 1: How Branches Work


• Example:
○ Version 1 & 2 = commits on main branch
○ Create a new branch (e.g., alien-plot) → x
○ Main branch continues as usual with stable updates
• Branches run parallel to each other → f x ✅

Step 2: Merging Branches


• If your experimental branch is successful:
1. Switch to main:

git checkout main


2. Merge changes from your branch:

git merge alien-plot


• Resolve any conflicts if necessary
• Commit message may appear in editor (Vim) → q w :q!
• Changes from alien-plot are now integrated into main

Step 3: Branch Commands


Task Command
Create branch git branch branch-name
List branches git branch
Switch branch git checkout branch-name
Merge branch git merge branch-name
View commits git log
• Asterisk (*) shows the current branch

Step 4: Branching Example


1. Create new branch:

git branch alien-plot


git checkout alien-plot
2. Modify files (e.g., Chapter 1 & 2) → :

Git^JGitHub and Verson Control Page 189


2. Modify files (e.g., Chapter 1 & 2) → :

git add .
git commit -m "modify chapter 1 and 2 to have alien theme"
3. Switch back to main branch:

git checkout main


4. Make other changes (e.g., add Chapter 4) → :

git add .
git commit -m "add chapter 4"
5. Merge experimental branch into main:

git merge alien-plot


6. Push changes to remote repository:

git push -u origin main

Step 5: Visualizing Branches


• Main branch = stable code
• Experimental branch = new ideas
• Merge successful experiments → b
• GitHub Network Graph shows branch & merge history

Key Takeaways
1. Branching = safe experimentation without affecting main branch ✅
2. Merging = integrate successful experiments back into main branch
3. Always check current branch with git branch before committing ✨
4. Push merged changes to remote repository to sync with GitHub
5. Large projects often have multiple active branches for features & bug fixes

Pro Tip:
• Think of branches like side roads:
○ You can explore new ideas without disrupting the highway (main branch)
○ Merge your detour back if it turns out to be a great path

Git^JGitHub and Verson Control Page 190


Untitled
Wednesday, September 3, 2025 12:06 PM

GitHub Collaboration: Forking & Pull Requests

Scenario
• You own a remote repository on GitHub (Angela)
• Someone else (Bangela) wants to propose changes
• Direct write access = trusted contributors only
• Others can suggest changes via Forks + Pull Requests

Step 1: Forking
• Fork = duplicate a remote repository into your own GitHub account
• Gives you full permissions on your copy
• Original repository remains protected from untrusted changes
Workflow:
1. Find the repository you want to contribute to
2. Click Fork → y w x y
3. Clone your fork locally if needed:

git clone <forked-repo-url>

Step 2: Make Changes


• Edit files locally (or directly on GitHub)
• Commit changes to your fork:

git add .
git commit -m "Add space themes to chapter 4"
git push origin master

Step 3: Pull Request (PR)


• Pull Request = request for the original repository owner to pull your changes
• Only the repository owner or trusted collaborators can merge PRs
• PR = suggestion, not a direct push
Creating a PR:
1. Go to your forked repository
2. Click Pull Request → b y f
3. Add title & description for the proposed changes
4. Submit → w y w w

Step 4: Reviewing & Merging


• Original repo owner can:
○ Review code differences & commit messages
○ Add comments or feedback
○ Approve & merge PR
• After merging:
○ Your changes appear in the original repo
○ Forked branch remains separate
• Example command-line confirmation not needed here GitHub handles merge automatically

Git^JGitHub and Verson Control Page 191



• Example command-line confirmation not needed here GitHub handles merge automatically

Key GitHub Concepts


Concept Description
Fork Duplicate a remote repo under your GitHub account
Pull Request Suggest changes from your fork to original repo
Merge Integrate approved PR into original repository
Write Access Permission to directly commit to a repo
Read Access Can view & clone, but cannot push changes

Collaboration Tips
• Fork → →P → w kf w = f
• Contributions can range from:
○ Simple edits (README, docs)
○ Bug fixes
○ Feature additions
• GitHub network graphs visualize fork & merge history
• Review & feedback are essential → f teamwork & learning

Real-Life Example
• Forked Story repo → fy chapter 4
• Commit changes on fork → → P
• Original owner reviews & merges → f
• Shows contributor history & merges in GitHub Network graph

Benefits
• Safe collaboration without compromising main code
• Encourages open-source contribution
• Learn teamwork & code review process
• Build reputation in developer community

Pro Tip:
• Start contributing by forking libraries you use → fx →P →
gradual larger contributions
• Treat GitHub like a social network for developers

Git^JGitHub and Verson Control Page 192

You might also like