Tuesday, March 18, 2025

Software Development Handout for Beginers

 First Month week 1 

Day One: Introduction to Software Development & HTML Basics


1. What is Software Development?

Software development is the process of creating, designing, and maintaining software applications. It involves writing code, testing, and improving software to meet user needs.

๐Ÿ‘‰ Example: Developing a mobile app, website, or computer program.


2. How Software Development Works

Software development follows a process called the Software Development Life Cycle (SDLC):

  1. Planning – Understanding the problem.
  2. Designing – Creating a blueprint (wireframe, UI design).
  3. Coding – Writing the actual program.
  4. Testing – Checking for errors (bugs).
  5. Deployment – Releasing the software for use.
  6. Maintenance – Updating and fixing issues.

3. Software Needed for Software Development

To start coding, you need:

  • Text Editor – VS Code, Sublime Text, Notepad++.
  • Web Browser – Chrome, Firefox.
  • Programming Languages – HTML, CSS, JavaScript.
  • Local Server (optional) – XAMPP for PHP projects.

4. Introduction to Websites Using Coding

A website is a collection of web pages displayed on the internet.
To create a website, we use:

  • HTML (HyperText Markup Language) – Structure
  • CSS (Cascading Style Sheets) – Styling
  • JavaScript – Interaction & Functionality

5. How to Create and Edit an HTML Page

๐Ÿ”น Open Notepad or VS Code
๐Ÿ”น Type the following HTML code:

html

CopyEdit

<!DOCTYPE html>

<html>

<head>

    <title>My First Web Page</title>

</head>

<body>

    <h1>Welcome to My Website</h1>

    <p>This is my first webpage.</p>

</body>

</html>

๐Ÿ”น Save the file as index.html
๐Ÿ”น Open it in a web browser.


6. Introduction to Tags and Elements

๐Ÿ”น Tags: Keywords in HTML that define elements.
๐Ÿ”น Elements: The content enclosed within tags.

๐Ÿ‘‰ Example:

html

CopyEdit

<p>This is a paragraph.</p>

  • <p> is a tag
  • This is a paragraph. is the content
  • <p>...</p> forms an element

7. Basic HTML Structure

Every HTML page follows this structure:

html

CopyEdit

<!DOCTYPE html>

<html>

<head>

    <title>Page Title</title>

</head>

<body>

    <h1>Main Heading</h1>

    <p>Paragraph content.</p>

</body>

</html>

๐Ÿ”น DOCTYPE – Declares HTML version.
๐Ÿ”น <html> – The root of an HTML document.
๐Ÿ”น <head> – Contains metadata & title.
๐Ÿ”น <body> – Contains the visible content.


8. Difference Between a Tag and an Element

Feature

Tag

Element

Definition

An HTML keyword enclosed in < >

A tag with content inside

Example

<h1>

<h1>Heading</h1>

Types

Opening & Closing tags

Empty or Container elements


9. How to Write HTML Tags and Elements

๐Ÿ”น Always use opening and closing tags (<tag>content</tag>)
๐Ÿ”น Some tags don’t need closing (
<br>, <img>).

Example:

html

CopyEdit

<h2>This is a heading</h2>

<img src="image.jpg" alt="My Image">


10. HTML Tags and Their Functionality

Tag

Function

<h1> - <h6>

Headings (Largest to Smallest)

<p>

Paragraph

<a href="#">

Hyperlink

<img src="path.jpg">

Image

<ul> <li>

Unordered List

<ol> <li>

Ordered List

<table>

Table Structure


Class Activities:

  1. Write & Save a simple HTML page.
  2. Identify different HTML tags in an example.
  3. Discuss how websites work using HTML.

Day One Assignment – Software Development & HTML Basics

Part A: Theory Questions

  1. What is software development? Give two examples of software.

  2. List and explain the six stages of the Software Development Life Cycle (SDLC).

  3. Mention three tools/software needed to start coding.

  4. Differentiate between:
    a. A tag and an element in HTML.
    b. An opening tag and a closing tag.

  5. State the function of the following HTML tags:

    • <h1>

    • <p>

    • <a>

    • <img>

    • <ul> and <ol>


Part B: Practical Tasks

  1. Create a simple HTML page using Notepad or VS Code that contains:

    • A main heading with your name.

    • A paragraph about why you want to learn web development.

    • An image (use any picture on your computer, e.g., image.jpg).

    • A link to your favorite website.

    ๐Ÿ‘‰ Save it as index.html and open it in your browser.

  2. Write HTML code that creates:

    • An unordered list of three fruits.

    • An ordered list of three school subjects.

  3. Identify HTML tags and elements in the following code (write which part is the tag, and which part is the element):

    <h2>Welcome to Coding</h2> <p>Coding makes websites work.</p>

Part C: Mini Project

Build a Simple Personal Profile Webpage that should include:

  • Your name as the main heading (<h1>).

  • A short paragraph about yourself.

  • A list of your hobbies (use <ul>).

  • A list of your three favorite subjects (use <ol>).

  • A picture (use <img>).

  • A link to any website you like (use <a>).

๐Ÿ‘‰ Save it as profile.html.


Day Two: Anchor link and List Tags in HTML

1. Anchor Link (<a> Tag)

The anchor (<a>) tag is used to create hyperlinks in HTML.
Example:

html
CopyEdit
<a href="https://www.google.com">Visit Google</a>

๐Ÿ”น href="URL" → Specifies the link destination.
๐Ÿ”น Example (Linking to another page on your site):

html
CopyEdit
<a href="about.html">About Us</a>

๐Ÿ”น Example (Link opening in a new tab):

html
CopyEdit
<a href="https://www.google.com" target="_blank">Visit Google</a>

 List Tags in HTML

1. What are Lists in HTML?

Lists in HTML are used to display items in an organized way.
Each item in a list is written inside the <li> tag.

๐Ÿ‘‰ Example:

<li>Apple</li> <li>Banana</li> <li>Orange</li>

2. Types of Lists in HTML

There are three main types of lists:

a. Ordered List (<ol>)

  • What: A numbered list.

  • Why: To show items in a sequence or ranking.

  • Where: Steps, instructions, or rankings.

  • How: Use <ol> and put list items inside <li>.

๐Ÿ‘‰ Example:

<ol> <li>Wake up</li> <li>Brush teeth</li> <li>Eat breakfast</li> </ol>

✅ Output:

  1. Wake up

  2. Brush teeth

  3. Eat breakfast


b. Unordered List (<ul>)

  • What: A bulleted list.

  • Why: To show items without order.

  • Where: Hobbies, shopping lists, features.

  • How: Use <ul> and put list items inside <li>.

๐Ÿ‘‰ Example:

<ul> <li>Football</li> <li>Reading</li> <li>Drawing</li> </ul>

✅ Output:

  • Football

  • Reading

  • Drawing


c. Description List (<dl>)

  • What: A list that describes terms with definitions.

  • Why: To explain words or concepts.

  • Where: Glossaries, product details, FAQs.

  • How: Use <dl> (description list), <dt> (term), and <dd> (description).

๐Ÿ‘‰ Example:

<dl> <dt>HTML</dt> <dd>The language for creating web pages.</dd> <dt>CSS</dt> <dd>Used for styling web pages.</dd> </dl>

✅ Output:
HTML – The language for creating web pages.
CSS – Used for styling web pages.


3. Class Activities

  1. Create an ordered list of your daily routine.

  2. Create an unordered list of your five favorite foods.

  3. Use a description list to explain three computer terms.


4. Mini Project

My Shopping List Page

  • Create an HTML page called shopping.html.

  • Add a heading: "My Shopping List".

  • Add an unordered list of 5 items to buy.

  • Add an ordered list of 3 steps to prepare for shopping.

  • Add a description list explaining at least 2 items (e.g., Rice – A staple food).


Day Three: Tables in HTML

Tables in HTML

1. What is a Table in HTML?

A table is a way of displaying data in rows and columns on a webpage.

๐Ÿ‘‰ Example in real life: Student results, price lists, timetables.


2. Why Use Tables?

  • To arrange information neatly.

  • To make data easy to read.

  • To show comparisons.


3. Table Tags and Their Functions

TagMeaningFunction
<table>TableStarts and ends the table
<tr>Table RowCreates a new row
<td>Table DataCreates a data cell (normal cell)
<th>Table HeaderCreates a heading cell (bold and centered by default)
<caption>Table CaptionAdds a title to the table
<thead>Table HeadGroups the header rows
<tbody>Table BodyGroups the main content rows
<tfoot>Table FooterGroups the footer rows

4. Simple Table Example

<table border="1"> <tr> <th>Name</th> <th>Age</th> <th>Class</th> </tr> <tr> <td>John</td> <td>12</td> <td>JS1</td> </tr> <tr> <td>Mary</td> <td>13</td> <td>JS2</td> </tr> </table>

✅ Output:

NameAgeClass
John12JS1
Mary13JS2

5. Adding Caption to a Table

<table border="1"> <caption>Student Details</caption> <tr> <th>Name</th> <th>Age</th> </tr> <tr> <td>Ada</td> <td>14</td> </tr> </table>

6. Using thead, tbody, and tfoot

<table border="1"> <thead> <tr> <th>Subject</th> <th>Score</th> </tr> </thead> <tbody> <tr> <td>Math</td> <td>80</td> </tr> <tr> <td>English</td> <td>75</td> </tr> </tbody> <tfoot> <tr> <td>Total</td> <td>155</td> </tr> </tfoot> </table>

7. Class Activities

  1. Create a table of 5 friends showing their name, age, and favorite food.

  2. Create a table with 3 rows and 3 columns showing your school subjects and marks.

  3. Add a caption to the table saying "My School Report".


8. Mini Project

Student Report Table

  • Create an HTML page called report.html.

  • Add a table with these columns: Name, Mathematics, English, Science, Total.

  • Fill in the data for at least 3 students.

  • Add a caption: "Class Report Sheet".

 Day four: Forms in HTML

1. What is a Form in HTML?

A form is used in HTML to collect input from users (like text, numbers, options).
๐Ÿ‘‰ Example in real life: Login form, registration form, feedback form.


2. Why Use Forms?

  • To collect user data (name, email, password, etc.).

  • To allow interaction between users and websites.

  • Forms are the main way websites receive information from visitors.


3. Basic Form Tag

The main container is the <form> tag.

<form> <!-- form elements go here --> </form>

4. Common Form Elements

TagMeaningExample
<input type="text">Single-line text fieldName, Username
<input type="password">Hidden charactersPassword
<input type="email">Email address fieldexample@mail.com
<input type="number">Numbers onlyAge, Phone
<input type="radio">Select one optionGender (Male/Female)
<input type="checkbox">Select multiple optionsHobbies
<textarea>Multi-line textComments, Messages
<select> <option>Drop-down listChoose Country
<button> or <input type="submit">Button to send dataSubmit form

5. Simple Form Example

<form> <label for="name">Name:</label> <input type="text" id="name" placeholder="Enter your name"><br><br> <label for="email">Email:</label> <input type="email" id="email" placeholder="Enter your email"><br><br> <label for="password">Password:</label> <input type="password" id="password"><br><br> <input type="submit" value="Submit"> </form>

✅ Output: A small form with fields for name, email, and password.


6. Radio Buttons Example

<p>Gender:</p> <input type="radio" name="gender" value="Male"> Male <input type="radio" name="gender" value="Female"> Female

7. Checkbox Example

<p>Hobbies:</p> <input type="checkbox" value="Reading"> Reading <input type="checkbox" value="Football"> Football <input type="checkbox" value="Drawing"> Drawing

8. Dropdown Example

<label for="country">Choose Country:</label> <select id="country"> <option value="nigeria">Nigeria</option> <option value="ghana">Ghana</option> <option value="kenya">Kenya</option> </select>

9. Class Activities

  1. Create a simple form with fields for Name, Age, and Email.

  2. Add radio buttons for gender selection.

  3. Add checkboxes for hobbies.

  4. Add a submit button.


10. Mini Project

Student Registration Form

  • Create a page register.html.

  • Add fields for: Name, Email, Password, Age.

  • Add a radio button for Gender.

  • Add checkboxes for Hobbies.

  • Add a drop-down for Class (e.g., JSS1, JSS2, JSS3).

  • Add a Submit button.


Day 5 Project

Week Project: Student Profile Website

Project Title:

๐Ÿ“Œ My Personal Student Website


Project Requirements

Students should create a single website with the following sections:

1. Homepage (index.html)

  • Add a heading with your name (<h1>).

  • Add a paragraph introducing yourself.

  • Add an image (your photo or any picture).

  • Add a link to your email or a favorite website.


2. My Hobbies Page (hobbies.html)

  • Use an unordered list to show at least 5 hobbies.

  • Use an ordered list to show your daily routine.

  • Use a description list to explain at least 3 school subjects.


3. My School Report Page (report.html)

  • Create a table with columns: Subject, Score, Grade.

  • Add at least 5 subjects with scores.

  • Add a caption: "My Report Sheet".


4. Registration Page (register.html)

  • Create a form with these fields:

    • Full Name (text)

    • Age (number)

    • Gender (radio buttons)

    • Hobbies (checkboxes)

    • Class (dropdown: JSS1, JSS2, JSS3)

    • Submit button


Navigation (Optional Challenge)

๐Ÿ‘‰ Add links at the top of each page so you can move between Homepage, Hobbies, Report, and Registration.

Example:

<a href="index.html">Home</a> | <a href="hobbies.html">Hobbies</a> | <a href="report.html">Report</a> | <a href="register.html">Register</a>

Expected Skills Used

  • Headings, Paragraphs, Links, and Images (HTML basics)

  • Ordered, Unordered, and Description Lists

  • Tables (rows, columns, headers, caption)

  • Forms (text, email, password, radio, checkbox, dropdown, submit)


Final Deliverable

By the end of the week, students should have a mini website with 4 pages connected together, showing they can use all the HTML basics.


Week Two Lesson Plan: HTML & CSS



Week 2: Introduction to CSS


Day 1: What is CSS?

  • Definition: CSS (Cascading Style Sheets) is used to style HTML elements (colors, fonts, layout).

  • Why CSS?

    • Makes websites look attractive.

    • Separates structure (HTML) from design (CSS).

  • Where is CSS used? Websites, web apps, online forms, etc.

  • How to use CSS?

    1. Inline CSS – style inside an HTML tag.

      <p style="color:blue;">This is blue text</p>
    2. Internal CSS – style inside <style> in the <head>.

      <style> p { color: green; } </style>
    3. External CSS – style in a separate .css file linked with <link>.

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

Activity: Write a paragraph in 3 different colors using inline, internal, and external CSS.


Day 2: CSS Selectors

  • Selectors tell CSS which element to style.

  1. Element Selector

    p { color: red; }

    Changes all <p> to red.

  2. ID Selector (#)

    #special { color: blue; }

    Targets one element with id="special".

  3. Class Selector (.)

    .highlight { background-color: yellow; }

    Targets all elements with class="highlight".

Activity: Style headings with ID, paragraphs with class, and one with element selector.


Day 3: CSS Properties

  • Text Properties: color, font-size, font-family, text-align.

  • Background Properties: background-color, background-image.

  • Box Model: margin, padding, border.

๐Ÿ‘‰ Example:

h1 { color: blue; text-align: center; background-color: lightgray; padding: 10px; border: 2px solid black; }

Activity: Create a heading with border, padding, and background color.


Day 4: CSS Colors & Units

  • Colors: By name (red), HEX (#ff0000), RGB (rgb(255,0,0)), HSL.

  • Units:

    • px (pixels, fixed size)

    • % (relative size)

    • em/rem (relative to font size)

๐Ÿ‘‰ Example:

p { color: #008000; font-size: 20px; }

Activity: Write 3 paragraphs, each styled with different colors and font sizes.


Day 5: Mini Project

Student Profile (Styled with CSS)

  • Use the profile.html from Week 1.

  • Add background color to the page.

  • Style the heading (different color, center aligned, bigger font).

  • Style the paragraph with a font-family of your choice.

  • Style the image (border + width).

  • Add a button and style it (background, color, padding).


Expected Outcome by End of Week 2

Students will:

  • Know what CSS is and why it is used.

  • Understand inline, internal, and external CSS.

  • Use selectors (element, ID, class).

  • Style text, backgrounds, and boxes.

  • Create a styled profile webpage.

Week Three Lesson Plan: Advanced HTML & CSS


Day One: Advanced Attributes in HTML & CSS

1. Introduction to Attributes and Values

Attributes provide additional information about HTML elements.
๐Ÿ”น Example:

html
CopyEdit
<img src="image.jpg" alt="Sample Image">
<a href="https://www.google.com" target="_blank">Visit Google</a>
  • src: Specifies the image source.
  • alt: Alternative text for images.
  • href: Defines the link URL.
  • target="_blank": Opens the link in a new tab.

2. Typesetting in CSS

CSS provides properties for text styling:
๐Ÿ”น Example:

css
CopyEdit
h1 {
    font-family: Arial, sans-serif;
    font-size: 24px;
    font-weight: bold;
    text-align: center;
    text-transform: uppercase;
}

3. Color in CSS

Colors can be added using names, HEX, RGB, or HSL.
๐Ÿ”น Example:

css
CopyEdit
p { color: red; } /* Named color */
p { color: #ff0000; } /* HEX color */
p { color: rgb(255, 0, 0); } /* RGB */

4. Background Color and Image

๐Ÿ”น Example:

css
CopyEdit
body {
    background-color: lightblue;
    background-image: url("background.jpg");
    background-size: cover;
}

week 3: Borders, Margins, and Padding in CSS

1. What is a Border?

A border surrounds an element.
๐Ÿ”น Example:

css
CopyEdit
div {
    border: 2px solid black;
    border-radius: 10px;
}

2. What is Padding?

Padding is the space inside an element, between the content and the border.
๐Ÿ”น Example:

css
CopyEdit
div {
    padding: 20px;
    background-color: lightgray;
}

3. What is Margin?

Margin is the space outside an element, creating distance from others.
๐Ÿ”น Example:

css
CopyEdit
div {
    margin: 30px;
}

Nav Css code 
  • overflow: hidden; - Prevents list items from going outside of the list
  • background-color: #333333; - Adds a black background-color to the <ul> element
  • float: left; - Makes <li> elements float next to each other
  • display: block; - Allows us to specify padding, height, width, and margins to <a>
  • padding: 14px 16px; - Add some padding between each <a> element
  • text-decoration: none; -


Day 2: Forms with Class and ID Selectors

1. Introduction to Class and ID Selectors

๐Ÿ”น Class Selector: Applied to multiple elements.

css
CopyEdit
.form-input {
    border: 1px solid blue;
    padding: 5px;
}
html
CopyEdit
<input type="text" class="form-input">

๐Ÿ”น ID Selector: Unique to one element.

css
CopyEdit
#submit-btn {
    background-color: green;
    color: white;
}
html
CopyEdit
<button id="submit-btn">Submit</button>

2. Form Attributes and Values

๐Ÿ”น Common Attributes:

  • action: Defines where form data is sent.
  • method: Specifies HTTP method (GET or POST).
  • required: Makes input mandatory.

๐Ÿ”น Example:

html
CopyEdit
<form action="submit.php" method="post">
    <input type="text" placeholder="Enter name" required>
    <button type="submit">Submit</button>
</form>

 cssinput {

  border: none;

  background: transparent;

}


input:focus {

  outline: none;

  box-shadow: none;

}

Day 3: Advanced CSS (Simple Teaching)


1. Box Model

What is it?
Every HTML element is like a box with:

  • Content (text/picture inside)

  • Padding (space between content and border)

  • Border (line around the box)

  • Margin (space outside the box).

๐Ÿ‘‰ Example:

div { width: 200px; padding: 20px; border: 2px solid black; margin: 10px; }

2. Position

What is it?
Position tells the browser where to place an element on the page.

  • static → default (normal position)

  • relative → move a little from normal position

  • absolute → placed anywhere inside parent box

  • fixed → stays on screen when scrolling

  • sticky → sticks when scrolling.

๐Ÿ‘‰ Example:

.box { position: relative; top: 20px; left: 30px; }

3. Flexbox

What is it?
A simple way to arrange items in a row or column.

๐Ÿ‘‰ Example:

.container { display: flex; justify-content: space-around; } .item { width: 100px; height: 100px; background: lightblue; }

4. Grid

What is it?
Grid helps us arrange items in rows and columns (like a table).

๐Ÿ‘‰ Example:

.container { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 10px; } .box { background: lightgreen; padding: 20px; }

5. Small Project

๐Ÿ‘‰ Create a Profile Card Page with:

  • A box (using box model) for the card.

  • Profile picture + name centered (using Flexbox).

  • Two sections (About & Skills) in columns (using Grid).

  • Footer fixed at the bottom (using position: fixed).


✅ By end of Week 3, students can control spacing, move elements, arrange items in rows/columns, and make a simple web layout.

Week Four Lesson Plan: Introduction to JavaScript


Day One: JavaScript Basics

1. Introduction to JavaScript

JavaScript is a programming language used to make web pages interactive.
๐Ÿ”น Example:

<script>
    alert("Welcome to JavaScript!");
</script>

2. How to Use JavaScript with HTML

JavaScript can be added inside an HTML file using:

  • Inline JavaScript:
<button onclick="alert('Button Clicked!')">Click Me</button>
  • Internal JavaScript:
html
CopyEdit
<script>
    document.write("Hello, JavaScript!");
</script>
  • External JavaScript:
html
CopyEdit
<script src="script.js"></script>

3. Types of Rules in JavaScript

  • Syntax Rules: How JavaScript should be written.
  • Variable Naming Rules: Cannot start with a number.
  • Operators Rules: +, -, *, /, etc.

4. Variable Declaration and Assigning

๐Ÿ”น Using var, let, and const:

var name = "John"// Old way
let age = 25;       // Modern way
const PI = 3.14;    // Cannot be changed

Student Tasks

  1. Declare your name using var. Change it to another name and print both.

  2. Declare your age using let. Try to redeclare it and see what happens.

  3. Declare a constant value for gravity (9.8) using const. Try to change it.

  4. Summarize the difference between var, let, and const in your notebook.

JavaScript Operators

JavaScript operators are symbols used to perform operations on values and variables. They help you calculate numbers, compare values, assign data, and make decisions in your program.


1. Arithmetic Operators

These operators are used for mathematical calculations.

OperatorMeaningExampleResult
+Addition5 + 38
-Subtraction5 - 32
*Multiplication5 * 315
/Division6 / 23
%Modulus (Remainder)7 % 21
**Power2 ** 38

Example

let a = 10;
let b = 5;

console.log(a + b);
console.log(a - b);
console.log(a * b);
console.log(a / b);
console.log(a % b);
console.log(a ** b);

Why use it?

To perform calculations.

Where is it used?

  • Calculator apps

  • Banking systems

  • Student result systems

  • Shopping websites


Practical

let price = 500;
let quantity = 4;

let total = price * quantity;

console.log(total);

Output

2000

2. Assignment Operators

Used to assign values to variables.

OperatorMeaningExample
=Assignx = 5
+=Add and assignx += 2
-=Subtract and assignx -= 2
*=Multiply and assignx *= 2
/=Divide and assignx /= 2

Example

let age = 20;

age += 5;

console.log(age);

Output

25

Why use it?

To update variable values.


Practical

let balance = 1000;

balance -= 200;

console.log(balance);

Output

800

3. Comparison Operators

Compare two values.

OperatorMeaningExample
==Equal5 == "5"
===Strict Equal5 === "5"
!=Not Equal5 != 4
!==Strict Not Equal5 !== "5"
>Greater Than8 > 5
<Less Than3 < 5
>=Greater or Equal6 >= 6
<=Less or Equal4 <= 6

Example

let age = 18;

console.log(age >= 18);

Output

true

Why use it?

To make decisions.

Where?

  • Login systems

  • Exam grading

  • Voting systems


Practical

let score = 70;

console.log(score >= 50);

Output

true

4. Logical Operators

Used to combine conditions.

OperatorMeaning
&&AND
`
!NOT

Example

let age = 20;
let hasID = true;

console.log(age >= 18 && hasID);

Output

true

Why?

To check multiple conditions.


Practical

let username = "admin";
let password = "1234";

console.log(username == "admin" && password == "1234");

Output

true

5. Increment and Decrement Operators

Increase or decrease a value by 1.

OperatorMeaning
++Increase by 1
--Decrease by 1

Example

let x = 5;

x++;

console.log(x);

Output

6

Practical

let visitors = 100;

visitors++;

console.log(visitors);

Output

101

6. String Operator

The + operator joins text together.

Example

let firstName = "John";
let lastName = "Doe";

console.log(firstName + lastName);

Output

JohnDoe

How to Give Space Between Text

Use " " (a space inside quotes).

let firstName = "John";
let lastName = "Doe";

console.log(firstName + " " + lastName);

Output

John Doe

Another example:

let city = "Abuja";
let country = "Nigeria";

console.log(city + ", " + country);

Output

Abuja, Nigeria

How to Move Text to the Next Line

Use the newline character \n.

Example

console.log("Welcome\nJavaScript");

Output

Welcome
JavaScript

Example with Variables

let name = "Raheem";
let age = 25;

console.log("Name: " + name + "\nAge: " + age);

Output

Name: Raheem
Age: 25

7. Ternary Operator

A short way to write an if...else statement.

Syntax

condition ? valueIfTrue : valueIfFalse;

Example

let age = 18;

let result = age >= 18 ? "Adult" : "Child";

console.log(result);

Output

Adult

Practical Exercise 1

Write a program that calculates the total cost.

let price = 250;
let quantity = 3;

let total = price * quantity;

console.log("Total: $" + total);

Output

Total: $750

Practical Exercise 2

Display student information.

let name = "Amina";
let course = "Computer Science";

console.log("Student Name: " + name + "\nCourse: " + course);

Output

Student Name: Amina
Course: Computer Science

Practical Exercise 3

Check if a student passed.

let score = 60;

let result = score >= 50 ? "Pass" : "Fail";

console.log(result);

Output

Pass

Summary

Operator TypePurpose
ArithmeticPerform calculations
AssignmentStore or update values
ComparisonCompare values
LogicalCombine conditions
Increment/DecrementIncrease or decrease a value
String (+)Join text together
Space (" ")Add a space between words
New Line (\n)Display text on the next line
TernaryShort form of if...else

Practice Challenge

Create a JavaScript program that:

  1. Stores your name and age in variables.

  2. Prints them on separate lines using \n.

  3. Joins your first and last name with a space.

  4. Calculates the total cost of 5 books at $15 each.

  5. Checks whether your age is 18 or above and prints "Adult" or "Minor" using the ternary operator.


Day 2. Introduction to Functions

Step 1: Function Declaration(no PARAMETER)

function greet() {

    console.log("Hello, welcome to JavaScript!");

}

 

greet();  // Call the function

✅ Observe: A function can be declared and then called to run the code inside.


๐Ÿ”น Step 2: Function with Parameters

function greetUser(name) {

    console.log("Hello " + name + ", nice to meet you!");

}

 

greetUser("John");   // Hello John, nice to meet you!

greetUser("Mary");   // Hello Mary, nice to meet you!

✅ Observe: Functions can take parameters (inputs).


๐Ÿ”น Step 3: Function with Return Value

function add(a, b) {

    return a + b;

}

 

let sum = add(5, 7);

console.log("The sum is: " + sum);   // The sum is: 12

✅ Observe: Functions can return a value.


๐ŸŽฏ Student Tasks

  1. Write a function called myName() that prints your name.
  2. Write a function called square(number) that returns the square of a number.
  3. Write a function called areaOfRectangle(length, width) that returns the area.
  4. Write a function called greetUser(name) and call it with your name.

✅ Expected Output

Hello, welcome to JavaScript!

Hello John, nice to meet you!

Hello Mary, nice to meet you!

The sum is: 12


Day 3: Conditional Statements & Loops

1. if Statement

What is it?
The if statement checks if a condition is true.

Why?
We use it when we want some code to run only when a condition is met.

Where?

  • Checking if a user is old enough to register.

  • Checking if a password is correct.

How?

let age = 18; if (age >= 18) { console.log("You are an adult."); }

✅ If age >= 18, the message will display.


2. if...else

What is it?
It provides two choices: one if the condition is true, another if false.

Why?
Because sometimes we need to decide between two options (pass/fail, yes/no).

Where?

  • Pass or fail results.

  • Show login success or error.

How?

let mark = 45; if (mark >= 50) { console.log("You passed!"); } else { console.log("You failed."); }

✅ If mark is 50 or above → Passed. Otherwise → Failed.


3. if...else if...else

What is it?
It checks many conditions one after another.

Why?
We use it when there are more than two outcomes.

Where?

  • Grading students (A, B, C, Fail).

  • Setting ticket prices (child, adult, senior).

How?

let score = 75; if (score >= 80) { console.log("Grade A"); } else if (score >= 60) { console.log("Grade B"); } else if (score >= 40) { console.log("Grade C"); } else { console.log("Fail"); }

✅ The program checks each condition until it finds the correct one.


4. switch Statement

What is it?
A cleaner way to choose between many fixed values.

Why?
It makes the code look neater than using many else if.

Where?

  • Days of the week.

  • Menu options in an app.

How?

let day = 3; switch(day) { case 1: console.log("Monday"); break; case 2: console.log("Tuesday"); break; case 3: console.log("Wednesday"); break; default: console.log("Invalid day"); }

✅ The program matches the number to the correct day.


Day 4: LOOPS


1. for Loop

What is it?
A loop that repeats code a fixed number of times.

Why?
Because we don’t want to write the same code again and again.

Where?

  • Printing numbers from 1 to 100.

  • Showing all items in a shopping cart.

How?

for (let i = 1; i <= 5; i++) { console.log("Number: " + i); }

✅ Runs 5 times and prints numbers 1 to 5.


2. while Loop

What is it?
A loop that runs as long as the condition is true.

Why?
When we don’t know how many times the loop should run in advance.

Where?

  • Asking for a correct password until entered.

  • Waiting for a task to finish.

How?

let i = 1; while (i <= 5) { console.log("Count: " + i); i++; }

✅ Keeps running until i is greater than 5.


3. do...while Loop

What is it?
A loop that runs at least once before checking the condition.

Why?
When you want the code to run at least once, even if the condition is false.

Where?

  • Showing a menu at least once.

  • Asking a question at least once.

How?

let x = 1; do { console.log("Step: " + x); x++; } while (x <= 5);

✅ Runs first, then checks the condition.


๐ŸŽฏ Student Tasks

  1. Write a program using if...else to check if a number is even or odd.

  2. Write a program using if...else if...else to grade marks:

    • 70+ = A

    • 50–69 = B

    • 40–49 = C

    • Below 40 = F

  3. Use a for loop to print numbers 1 to 10.

  4. Use a while loop to print numbers 10 down to 1.

  5. Use a do...while loop to print your name 5 times

3. User Input and Basic Interactions

1. Using prompt() to Collect User Input

The prompt() function asks the user to type something.

Example:

let name = prompt("What is your name?");
alert("Welcome, " + name + "!");

How It Works:

  1. prompt() opens a small input box.

  2. The user types their name.

  3. The result is stored in the name variable.

  4. alert() shows the result.


2. Using alert() to Display Results

The alert() function shows messages to the user.

Example:

alert("JavaScript makes websites fun!");

3. Using confirm() for Yes/No Questions

The confirm() function asks a Yes/No question and returns true or false.

Example:

let like = confirm("Do you like JavaScript?");
if (like) {
    alert("That's great! Keep learning.");
} else {
    alert("Don't worry, you'll enjoy it soon!");
}

4. Performing Basic Calculations

We can use JavaScript to calculate numbers entered by the user.

Example – Simple Calculator:

let num1 = prompt("Enter first number:");
let num2 = prompt("Enter second number:");

num1 = Number(num1);
num2 = Number(num2);

let sum = num1 + num2;
alert("The sum is: " + sum);

5. Mini Project – Shopping Bill Calculator

Goal: Create a program where the user enters product prices, and the total bill is displayed.

Step-by-Step Code:

// Step 1: Ask the user for three product prices
let item1 = Number(prompt("Enter price of item 1:"));
let item2 = Number(prompt("Enter price of item 2:"));
let item3 = Number(prompt("Enter price of item 3:"));

// Step 2: Calculate total
let total = item1 + item2 + item3;

// Step 3: Display total bill
alert("Your total bill is: ₦" + total);

// Step 4: Ask if user wants to proceed with payment
let payNow = confirm("Do you want to make payment?");
if (payNow) {
    alert("Payment Successful ✅");
} else {
    alert("Please complete your payment later.");
}

6. Practice Exercises

  1. Write a program that asks the user for their age and displays a message:

    • If they are 18 or older → “You are eligible to vote.”

    • Otherwise → “You are too young to vote.”

  2. Create a program that asks the user for two numbers and displays:

    • Sum

    • Difference

    • Product

    • Division

  3. Make a program that asks for a student’s name and 3 subject scores, then displays their average.


8. Final Notes

  • Always convert user input to numbers using Number() when performing calculations.

  • Test your code in the browser console or a .html file.

  • Practice regularly to improve.


JavaScript Objects (Beginner Guide)


Topic 1: What is a JavaScript Object?

Meaning

A JavaScript object is a collection of related data and functions stored together under one name.

An object is used to describe a real-world thing by grouping all its information into one place.

For example, a student has:

  • Name

  • Age

  • Course

  • Level

Instead of creating separate variables for each piece of information, we can store them together in one object.


Why is it called an Object?

It is called an object because it represents a real-world object or entity.

Examples:

  • A student

  • A car

  • A phone

  • A book

  • A customer

Each object has properties (information) and can also have methods (actions).


Why do we use Objects?

Without objects, we would create many separate variables.

Example without an object:

let name = "John";
let age = 20;
let course = "Computer Science";
let level = "200 Level";

This becomes difficult to manage as the program grows.

Using an object:

let student = {
    name: "John",
    age: 20,
    course: "Computer Science",
    level: "200 Level"
};

Everything about the student is stored in one place.


Where are Objects Used?

Objects are used in almost every JavaScript program, including:

  • Student management systems

  • Banking applications

  • E-commerce websites

  • Hospital systems

  • School portals

  • Social media platforms


Example

let student = {
    name: "John",
    age: 20
};

console.log(student);

Output

{ name: "John", age: 20 }

Why is it like that?

The { } (curly braces) tell JavaScript that you are creating an object.

Inside the object:

  • name and age are called properties (they store information).

  • "John" and 20 are the values of those properties.


Practical

let car = {
    brand: "Toyota",
    color: "Black",
    year: 2024
};

console.log(car);

Topic 2: Object Properties

Meaning

A property is a piece of information stored inside an object.

Think of properties as the characteristics of an object.


Example

let phone = {
    brand: "Samsung",
    model: "Galaxy S25",
    color: "Blue"
};

Here,

  • brand

  • model

  • color

are properties.


Why?

Every object needs information to describe it.

Without properties, the object would contain no useful data.


Practical

let book = {
    title: "JavaScript Basics",
    author: "James",
    pages: 250
};

console.log(book);

Topic 3: Accessing Object Properties

Meaning

To use the information stored in an object, you must access its properties.

There are two ways to access a property.


Method 1: Dot Notation (.)

Example

let student = {
    name: "John",
    age: 20
};

console.log(student.name);

Output

John

Why?

The dot (.) tells JavaScript:

"Go inside the student object and get the name property."


Method 2: Bracket Notation ([])

Example

let student = {
    name: "John",
    age: 20
};

console.log(student["age"]);

Output

20

Why?

The brackets allow you to access a property using its name as a string.


Practical

let laptop = {
    brand: "HP",
    ram: "16GB"
};

console.log(laptop.brand);
console.log(laptop["ram"]);

Topic 4: Changing Object Properties

Meaning

You can change the value of a property after the object has been created.


Example

let student = {
    name: "John"
};

student.name = "Mary";

console.log(student.name);

Output

Mary

Why?

Objects are mutable, which means their properties can be updated after creation.


Practical

let car = {
    color: "Red"
};

car.color = "Black";

console.log(car.color);

Topic 5: Adding New Properties

Meaning

You can add new information to an existing object.


Example

let student = {
    name: "John"
};

student.age = 20;

console.log(student);

Output

{ name: "John", age: 20 }

Why?

JavaScript objects are flexible. You are not limited to the properties defined when the object was created.


Practical

let phone = {
    brand: "Samsung"
};

phone.color = "Blue";

console.log(phone);

Topic 6: Removing Properties

Meaning

You can remove a property from an object using the delete keyword.


Example

let student = {
    name: "John",
    age: 20
};

delete student.age;

console.log(student);

Output

{ name: "John" }

Why?

The delete keyword removes the selected property from the object.


Practical

let car = {
    brand: "Toyota",
    color: "White"
};

delete car.color;

console.log(car);

Topic 7: Object Methods

Meaning

A method is a function stored inside an object.

Properties store information.

Methods perform actions.


Example

let person = {
    name: "John",

    greet: function () {
        console.log("Hello!");
    }
};

person.greet();

Output

Hello!

Why?

Instead of storing data only, an object can also store functions that describe what it can do.


Practical

let calculator = {
    add: function () {
        console.log(10 + 5);
    }
};

calculator.add();

Topic 8: Objects Inside Objects

Meaning

An object can contain another object.

This is called a nested object.


Example

let student = {
    name: "John",

    address: {
        city: "Abuja",
        country: "Nigeria"
    }
};

console.log(student.address.city);

Output

Abuja

Why?

Sometimes information naturally belongs together, such as an address containing a city and country.


Practical

let employee = {
    name: "Grace",

    office: {
        department: "ICT",
        floor: 3
    }
};

console.log(employee.office.department);

Topic 9: Looping Through Object Properties

Meaning

The for...in loop is used to go through every property in an object.


Example

let student = {
    name: "John",
    age: 20,
    course: "Computer Science"
};

for (let key in student) {
    console.log(key + ": " + student[key]);
}

Output

name: John
age: 20
course: Computer Science

Why?

The for...in loop automatically visits each property one by one, making it useful when you do not know how many properties an object has.


Practical

let phone = {
    brand: "Samsung",
    color: "Black",
    storage: "256GB"
};

for (let key in phone) {
    console.log(key + ": " + phone[key]);
}

Topic 10: Real-Life 

Meaning

Objects are ideal for storing related information about one thing.


Example

let student = {
    name: "Amina",
    age: 21,
    course: "Computer Science",
    level: "300 Level",

    introduce: function () {
        console.log("My name is " + this.name);
    }
};

student.introduce();

Output

My name is Amina

Why?

  • this.name refers to the name property of the current object.

  • The method can use the object's own data without repeating the object's name.


Summary

TopicPurpose
ObjectStores related data in one place
PropertiesHold information about the object
Dot Notation (.)Access a property
Bracket Notation ([])Access a property using a string
Update PropertiesChange existing values
Add PropertiesAdd new information
deleteRemove a property
MethodsFunctions inside an object
Nested ObjectsStore objects inside other objects
for...inLoop through all properties

Practice Challenge

Create a JavaScript object called student with the following:

  • name

  • age

  • course

  • level

Then:

  1. Display the student's name using dot notation.

  2. Display the course using bracket notation.

  3. Change the student's level.

  4. Add a new property called email.

  5. Delete the age property.

  6. Add a method called introduce() that displays "My name is [student name]".

  7. Use a for...in loop to display all the remaining properties and their values.

JavaScript Predefined Objects (Built-in Objects)


Topic 1: What Are Predefined Objects?

Meaning

Predefined objects (also called built-in objects) are objects that are already created by JavaScript. You do not need to create them yourself because they are built into the language.

They provide ready-made methods and properties that make programming easier.


Why are they called Predefined Objects?

They are called predefined because JavaScript already knows about them before your program starts.

Instead of writing your own code to calculate dates, perform mathematical operations, or manipulate text, JavaScript provides these objects for you.


Why do we use Predefined Objects?

They save time and reduce the amount of code you need to write.

For example, instead of creating your own clock system, JavaScript provides the Date object.


Where are they used?

Predefined objects are used in:

  • Digital clocks

  • Calendar applications

  • Banking systems

  • School management systems

  • E-commerce websites

  • Games

  • Login systems


Topic 2: Date Object (Time and Date)

Meaning

The Date object is used to work with dates and times.

It can display:

  • Current time

  • Current date

  • Day

  • Month

  • Year

  • Hours

  • Minutes

  • Seconds

It is commonly used to build digital clock projects.


Why do we use the Date Object?

Without the Date object, JavaScript would not know the current date or time.

It gets the date and time from the user's computer or device.


Creating a Date Object

let today = new Date();

console.log(today);

Example Output

Tue Jul 29 2026 08:30:25

Getting the Current Hour

let today = new Date();

console.log(today.getHours());

Example Output

8

Why?

getHours() returns only the hour from the current time.


Getting Minutes

let today = new Date();

console.log(today.getMinutes());

Example Output

30

Getting Seconds

let today = new Date();

console.log(today.getSeconds());

Example Output

25

Getting the Current Year

let today = new Date();

console.log(today.getFullYear());

Example Output

2026

Getting the Month

let today = new Date();

console.log(today.getMonth());

Example Output

6

Why?

Months start counting from 0 in JavaScript.

NumberMonth
0January
1February
2March
3April
4May
5June
6July
7August
8September
9October
10November
11December

So if getMonth() returns 6, it means July.


Practical: Digital Clock

function showTime() {
    let time = new Date();

    let hour = time.getHours();
    let minute = time.getMinutes();
    let second = time.getSeconds();

    console.log(hour + ":" + minute + ":" + second);
}

showTime();

Topic 3: Math Object

Meaning

The Math object performs mathematical calculations.

Unlike the Date object, you do not create it with new.


Why do we use the Math Object?

It provides ready-made mathematical functions.


Finding the Largest Number

console.log(Math.max(10, 20, 30));

Output

30

Finding the Smallest Number

console.log(Math.min(10, 20, 30));

Output

10

Rounding Numbers

console.log(Math.round(4.7));

Output

5

Random Number

console.log(Math.random());

Example Output

0.734521

Why?

Math.random() generates a random number between 0 and 1.


Practical

let number = Math.floor(Math.random() * 10) + 1;

console.log(number);

This generates a random number from 1 to 10.


Topic 4: String Object

Meaning

The String object helps us work with text.


Why?

Instead of writing your own code to count letters or change text, JavaScript provides string methods.


Finding the Length

let name = "Raheem";

console.log(name.length);

Output

7

Changing to Uppercase

let name = "javascript";

console.log(name.toUpperCase());

Output

JAVASCRIPT

Changing to Lowercase

let name = "JAVASCRIPT";

console.log(name.toLowerCase());

Output

javascript

Practical

let school = "Nobigdeal Academy";

console.log(school.length);
console.log(school.toUpperCase());

Topic 5: Number Object

Meaning

The Number object helps work with numbers.


Why?

It provides methods to format numbers.


Example

let price = 15.6789;

console.log(price.toFixed(2));

Output

15.68

Why?

toFixed(2) displays the number with 2 decimal places.


Practical

let amount = 120.4567;

console.log(amount.toFixed(2));

Output

120.46

Topic 6: Boolean Object

Meaning

A Boolean object represents only two values:

  • true

  • false


Why?

It is used when making decisions.


Example

let passed = true;

console.log(passed);

Output

true

Practical

let age = 20;

console.log(age >= 18);

Output

true

Topic 7: Array Object

Meaning

An Array stores multiple values in one variable.


Why?

Instead of creating many variables, we store similar values together.


Example

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

console.log(fruits);

Finding the Number of Items

console.log(fruits.length);

Output

3

Practical

let students = ["John", "Mary", "James"];

console.log(students[0]);

Output

John

Topic 8: JSON Object

Meaning

JSON stands for JavaScript Object Notation.

It is used to exchange data between applications and servers.


Why?

Most websites and APIs send and receive data in JSON format because it is lightweight and easy to read.


Convert Object to JSON

let student = {
    name: "John",
    age: 20
};

console.log(JSON.stringify(student));

Output

{"name":"John","age":20}

Convert JSON Back to an Object

let data = '{"name":"John","age":20}';

console.log(JSON.parse(data));

Output

{ name: "John", age: 20 }

Summary

Predefined ObjectPurposeExample
DateWork with date and timeDigital clock, calendar
MathMathematical calculationsCalculator, random numbers
StringManipulate textChange case, count characters
NumberFormat numbersDisplay decimal places
BooleanStore true or falseLogin checks, conditions
ArrayStore multiple valuesLists of students or products
JSONExchange dataAPIs, web applications

Practice Challenge

Create a JavaScript program that:

  1. Displays the current year, month, date, hour, minute, and second using the Date object.

  2. Generates a random number between 1 and 100 using the Math object.

  3. Converts your name to uppercase and displays its length using the String object.

  4. Formats a decimal number to 2 decimal places using the Number object.

  5. Stores five student names in an Array and displays the first and last names.

  6. Creates a student object, converts it to JSON, then converts it back to a JavaScript object.


JavaScript DOM (Document Object Model)


Topic 1: What is the DOM?

Meaning

DOM stands for Document Object Model.

The DOM is the way JavaScript sees and communicates with an HTML page. It converts every HTML element (such as headings, paragraphs, buttons, images, and forms) into objects that JavaScript can access and control.

Think of the DOM as a bridge between HTML and JavaScript.

  • HTML creates the webpage.

  • CSS styles the webpage.

  • JavaScript (using the DOM) makes the webpage interactive.


Why is it called the Document Object Model?

  • Document – The webpage (HTML document).

  • Object – Every HTML element becomes an object that JavaScript can work with.

  • Model – A structured representation of the webpage.


Why do we use the DOM?

Without the DOM, JavaScript cannot:

  • Change text

  • Change colors

  • Hide or show elements

  • Read user input

  • Respond to button clicks

  • Create or remove elements

The DOM allows JavaScript to control the webpage after it has loaded.


Where is it used?

The DOM is used in almost every website, including:

  • Login pages

  • Registration forms

  • Online shopping websites

  • School portals

  • Banking websites

  • Social media websites


Example

HTML

<h1 id="title">Welcome</h1>

JavaScript

document.getElementById("title").innerHTML = "Welcome to JavaScript";

Result

Before:

Welcome

After:

Welcome to JavaScript

Why is it like that?

  • document means the current HTML page.

  • getElementById("title") finds the element with id="title".

  • innerHTML changes the content inside that element.

JavaScript updates the webpage without reloading it.


Practical

HTML

<h2 id="message">Good Morning</h2>

<button onclick="changeText()">Click Me</button>

JavaScript

function changeText() {
    document.getElementById("message").innerHTML = "Good Evening";
}

When you click the button, the text changes from Good Morning to Good Evening.


Topic 2: Selecting HTML Elements

Meaning

Before JavaScript can change an element, it must first find that element.

This process is called selecting an element.


Why?

Imagine a classroom with 50 students.

If the teacher says,

"Stand up."

Everyone stands.

But if the teacher says,

"John, stand up."

Only John stands.

JavaScript works the same way.

It must know exactly which element to work with.


Selecting by ID

HTML

<p id="demo">Hello World</p>

JavaScript

document.getElementById("demo");

Why?

Because every ID should be unique.

JavaScript can quickly find that one element.


Practical

<p id="name">Raheem</p>

<button onclick="changeName()">Change</button>
function changeName() {
    document.getElementById("name").innerHTML = "Amina";
}

Topic 3: Changing Text (innerHTML)

Meaning

innerHTML changes everything inside an HTML element.


Example

<h1 id="title">Old Text</h1>
document.getElementById("title").innerHTML = "New Text";

Result

Before

Old Text

After

New Text

Why?

The word inner means inside.

So innerHTML changes whatever is inside the HTML tag.


Practical

<p id="status">Offline</p>

<button onclick="online()">Go Online</button>
function online() {
    document.getElementById("status").innerHTML = "Online";
}

Topic 4: Changing CSS Styles

Meaning

JavaScript can change the appearance of HTML elements.


Example

<p id="text">Learning JavaScript</p>
document.getElementById("text").style.color = "red";

Result

The text becomes red.


Why?

The style property gives JavaScript access to the CSS of an element.


Practical

document.getElementById("text").style.fontSize = "30px";

The text becomes larger.


Topic 5: Changing Images

Meaning

JavaScript can change an image while the page is open.


HTML

<img id="light" src="off.png">

JavaScript

document.getElementById("light").src = "on.png";

Why?

The src attribute tells the browser where the image is located.

Changing src changes the displayed image.


Practical

document.getElementById("light").src = "off.png";

Topic 6: Getting User Input

Meaning

JavaScript can read what the user types into an input field.


HTML

<input type="text" id="username">

<button onclick="showName()">Submit</button>

JavaScript

function showName() {

let name = document.getElementById("username").value;

alert(name);

}

Why?

The .value property stores the value entered into form elements like:

  • Text boxes

  • Password fields

  • Email fields

  • Number fields


Practical

If the user types

Raheem

The alert displays

Raheem

Topic 7: Button Events

Meaning

An event is something that happens on a webpage.

Examples:

  • Clicking a button

  • Typing on the keyboard

  • Moving the mouse

  • Loading the page

JavaScript can respond to these events.


HTML

<button onclick="welcome()">Click Me</button>

JavaScript

function welcome() {

alert("Welcome!");

}

Why?

The onclick event waits until the user clicks the button.

Only then does JavaScript execute the function.


Practical

<button onclick="sayHello()">Hello</button>
function sayHello() {

alert("Hello Student");

}

Topic 8: Showing and Hiding Elements

Meaning

JavaScript can hide or show HTML elements.


Hide

document.getElementById("box").style.display = "none";

Show

document.getElementById("box").style.display = "block";

Why?

The CSS display property controls whether an element appears on the page.

  • "none" hides it.

  • "block" displays it as a block element again.


Practical

<p id="box">This is a secret message.</p>

<button onclick="hideText()">Hide</button>
function hideText() {

document.getElementById("box").style.display = "none";

}

Topic 9: Creating HTML Elements

Meaning

JavaScript can create new HTML elements while the page is running.


Example

let heading = document.createElement("h2");

Why?

createElement() tells JavaScript to create a new HTML element, but it does not appear on the page until you add it to the document.


Practical

let p = document.createElement("p");

p.innerHTML = "Welcome to DOM";

Topic 10: Removing HTML Elements

Meaning

JavaScript can remove elements from the webpage.


HTML

<p id="note">Delete Me</p>

JavaScript

document.getElementById("note").remove();

Why?

The remove() method deletes the selected element from the DOM, so it disappears from the page.


Practical

<button onclick="deleteText()">Delete</button>

<p id="note">Learning JavaScript DOM</p>
function deleteText() {

document.getElementById("note").remove();

}

Summary

TopicPurpose
What is DOM?Connects JavaScript with HTML
Selecting ElementsFinds HTML elements
innerHTMLChanges text or HTML inside an element
styleChanges the appearance of elements
srcChanges an image
valueReads user input from form fields
onclickRuns code when a button is clicked
displayShows or hides elements
createElement()Creates new HTML elements
remove()Removes HTML elements

Practice Challenge

Create a webpage with:

  1. A heading that changes text when a button is clicked.

  2. A paragraph whose color changes to blue.

  3. An input box that displays the user's name in an alert.

  4. A button that hides a paragraph.

  5. Another button that shows the paragraph again.

  6. A button that creates a new paragraph saying "Welcome to JavaScript DOM!" and adds it to the page.

  7. A button that removes the newly created paragraph.

JavaScript Events


Topic 1: What Are JavaScript Events?

Meaning

A JavaScript event is an action or occurrence that happens on a webpage, and JavaScript can respond to it.

An event can be caused by:

  • A user clicking a button

  • Typing in a text box

  • Moving the mouse

  • Pressing a keyboard key

  • Loading a webpage

Think of an event as a signal that tells JavaScript:

"Something has happened. Do something now."


Why is it called an Event?

It is called an event because it happens at a particular time.

For example:

  • A button is clicked.

  • A key is pressed.

  • The mouse moves.

These actions are called events, and JavaScript listens for them.


Why do we use Events?

Without events, a webpage would be static.

Events allow users to interact with a webpage by:

  • Clicking buttons

  • Filling forms

  • Playing videos

  • Opening menus

  • Searching information

  • Logging into websites


Where are Events Used?

JavaScript events are used in:

  • Login pages

  • Registration forms

  • Shopping websites

  • Banking websites

  • School portals

  • Games

  • Social media websites


Example

HTML

<button onclick="welcome()">Click Me</button>

JavaScript

function welcome() {
    alert("Welcome to JavaScript!");
}

Result

When the button is clicked, a message box appears:

Welcome to JavaScript!

Why is it like that?

The onclick event waits for the user to click the button.

When the click happens, JavaScript runs the welcome() function.


Practical

<button onclick="sayHello()">Say Hello</button>

<script>
function sayHello() {
    alert("Hello Student!");
}
</script>

Topic 2: The onclick Event

Meaning

The onclick event happens when a user clicks an HTML element.


Why do we use onclick?

We use it because many actions should happen only after the user clicks something.

For example:

  • Submit a form

  • Open a menu

  • Change text

  • Show a message


Example

<button onclick="changeText()">Click</button>

<p id="demo">Welcome</p>
function changeText() {
    document.getElementById("demo").innerHTML = "Thank you for clicking!";
}

Practical

<button onclick="showName()">Show Name</button>

<script>
function showName() {
    alert("My name is John.");
}
</script>

Topic 3: The ondblclick Event

Meaning

The ondblclick event happens when a user double-clicks an element.


Why?

Some websites use a double-click to prevent accidental actions.


Example

<p ondblclick="changeColor()">Double-click me</p>
function changeColor() {
    document.body.style.backgroundColor = "yellow";
}

Practical

Double-click the text to change the background color.


Topic 4: The onmouseover Event

Meaning

The onmouseover event happens when the mouse pointer moves over an element.


Why?

It is used to:

  • Show extra information

  • Highlight buttons

  • Display menus


Example

<p onmouseover="hoverMessage()">Move the mouse here</p>
function hoverMessage() {
    alert("Mouse is over the text.");
}

Practical

Move your mouse over the paragraph and see the alert.


Topic 5: The onmouseout Event

Meaning

The onmouseout event happens when the mouse leaves an element.


Why?

It is commonly used to:

  • Hide menus

  • Remove highlights

  • Reset colors


Example

<p id="text"
onmouseover="red()"
onmouseout="black()">
Move your mouse here
</p>
function red() {
    document.getElementById("text").style.color = "red";
}

function black() {
    document.getElementById("text").style.color = "black";
}

Practical

Move the mouse over the text to make it red, then move it away to make it black again.


Topic 6: The onchange Event

Meaning

The onchange event happens when the value of an input, select box, or textarea changes and the user finishes editing it.


Why?

It allows JavaScript to react when a user changes information.


Example

<input type="text" onchange="showValue()">
function showValue() {
    alert("Value changed.");
}

Practical

Type something in the input box, then click outside it. The alert appears because the value changed.


Topic 7: The onkeyup Event

Meaning

The onkeyup event happens when the user releases a keyboard key.


Why?

It is useful for checking what the user has typed, such as:

  • Live search

  • Password strength

  • Character counting


Example

<input type="text" onkeyup="typing()">
function typing() {
    console.log("You released a key.");
}

Practical

Type in the input field and watch the messages appear in the browser console.


Topic 8: The onkeydown Event

Meaning

The onkeydown event happens when the user presses a keyboard key.


Why?

It can detect key presses before the key is released.


Example

<input type="text" onkeydown="pressed()">
function pressed() {
    console.log("Key pressed.");
}

Practical

Each time you press a key, the function runs.


Topic 9: The onsubmit Event

Meaning

The onsubmit event happens when a form is submitted.


Why?

It is used to:

  • Validate user input

  • Prevent empty forms

  • Check passwords

  • Save data


Example

<form onsubmit="submitForm()">
    <input type="text">
    <input type="submit">
</form>
function submitForm() {
    alert("Form submitted.");
}

Practical

Click the Submit button to display the alert.


Topic 10: The onload Event

Meaning

The onload event happens when a webpage has completely loaded.


Why?

It ensures everything on the page is ready before JavaScript runs.


Example

<body onload="welcome()">
function welcome() {
    alert("Page loaded successfully.");
}

Practical

Open the webpage, and the alert appears automatically after the page finishes loading.


Summary

EventMeaningWhy It Is Used
onclickUser clicks an elementPerform actions after a click
ondblclickUser double-clicksPrevent accidental actions
onmouseoverMouse moves over an elementShow information or highlight elements
onmouseoutMouse leaves an elementRemove highlights or hide menus
onchangeInput value changesReact to user input
onkeyupKey is releasedLive search, validation, typing checks
onkeydownKey is pressedDetect keyboard input immediately
onsubmitForm is submittedValidate and process forms
onloadWebpage finishes loadingRun code after the page is ready

Practice Challenge

Create a webpage that includes:

  1. A button that displays "Welcome to JavaScript Events!" when clicked (onclick).

  2. A paragraph that changes to blue when the mouse moves over it and back to black when the mouse leaves (onmouseover and onmouseout).

  3. A text input that shows an alert when its value changes (onchange).

  4. A text input that logs a message every time a key is released (onkeyup).

  5. A form that displays "Form submitted successfully!" when submitted (onsubmit).

  6. A welcome message that appears automatically when the page loads (onload).

JavaScript DOM Project: Add Items to a List and Delete Them


Topic: DOM Project – Add, Display, and Delete List Items

Meaning

In this project, you will learn how to use the DOM (Document Object Model) to:

  • Get text from a textbox.

  • Display the text as a list on the same HTML page.

  • Add new items when the Add button is clicked.

  • Delete an item when you click on it and confirm the deletion.

  • Delete an item using a separate Delete button.

This is similar to a simple To-Do List application.


Why do we use the DOM?

The DOM allows JavaScript to:

  • Read user input.

  • Create new HTML elements.

  • Display information without refreshing the page.

  • Remove HTML elements dynamically.

Without the DOM, the page cannot update itself after the user enters information.


Step 1: Create the HTML Page

<!DOCTYPE html>
<html>
<head>
    <title>Student List</title>
</head>
<body>

<h2>Student List</h2>

<input type="text" id="studentName" placeholder="Enter student name">

<button onclick="addStudent()">Add</button>

<ul id="studentList"></ul>

<script src="script.js"></script>

</body>
</html>

Explanation

Input Box

<input type="text" id="studentName">

Why?

This allows the user to type a student's name.


Button

<button onclick="addStudent()">Add</button>

Why?

When clicked, JavaScript runs the addStudent() function.


List

<ul id="studentList"></ul>

Why?

This is where all student names will appear.


Step 2: JavaScript Code

function addStudent() {

    let input = document.getElementById("studentName");

    let name = input.value;

    if (name == "") {
        alert("Please enter a name.");
        return;
    }

    let li = document.createElement("li");

    li.innerHTML = name;

    li.onclick = function () {

        let answer = confirm("Do you want to delete this item?");

        if (answer) {
            li.remove();
        }

    };

    let deleteButton = document.createElement("button");

    deleteButton.innerHTML = "Delete";

    deleteButton.onclick = function () {

        let answer = confirm("Do you want to delete this item?");

        if (answer) {
            li.remove();
        }

    };

    li.appendChild(deleteButton);

    document.getElementById("studentList").appendChild(li);

    input.value = "";

}

Explanation (Line by Line)

Get the Textbox

let input = document.getElementById("studentName");

Why?

JavaScript finds the textbox using its id.


Get the User's Text

let name = input.value;

Why?

The .value property reads what the user typed.

Example:

John

Check for an Empty Textbox

if(name == ""){

Why?

This prevents adding empty list items.

If nothing is typed, JavaScript displays:

Please enter a name.

Create a New List Item

let li = document.createElement("li");

Why?

The DOM creates a new <li> element.

It does not appear on the page until it is added.


Put the Name Inside the List

li.innerHTML = name;

Example

John

Now the list item contains:

<li>John</li>

Delete When Clicking the List Item

li.onclick = function () {

Why?

When the user clicks the student's name, JavaScript runs this function.


Ask for Confirmation

confirm("Do you want to delete this item?");

Why?

The confirm() function displays two buttons:

  • OK

  • Cancel

If the user clicks OK, JavaScript returns:

true

If the user clicks Cancel, JavaScript returns:

false

Remove the List Item

li.remove();

Why?

The remove() method deletes the selected list item from the page.


Create the Delete Button

let deleteButton = document.createElement("button");

Why?

Creates a button beside every student's name.


Button Text

deleteButton.innerHTML = "Delete";

The button now displays

Delete

Delete Button Event

deleteButton.onclick = function () {

Why?

When the Delete button is clicked, JavaScript asks for confirmation.


Add Button to the List Item

li.appendChild(deleteButton);

Why?

This places the Delete button inside the same <li> as the student's name.

Example:

John   Delete

Display the List Item

document.getElementById("studentList").appendChild(li);

Why?

The new list item is added to the <ul> so it appears on the page.


Clear the Textbox

input.value = "";

Why?

After adding a name, the textbox becomes empty, making it ready for the next entry.


Complete Output

Student List

-----------------------------
| Enter student name       |
-----------------------------
          [Add]

• John          Delete

• Mary          Delete

• James         Delete

If you click John

Do you want to delete this item?

OK     Cancel

If you click OK, John is removed from the list.


Practical Exercise

Modify the program to:

  1. Prevent duplicate names from being added.

  2. Display the total number of students below the list.

  3. Add an Edit button beside each student's name to allow changing the name.

  4. Display the names in alphabetical order after each new addition.


0 comments:

Post a Comment

 

BEST COMPUTER GUIDE Written by Abigail Odenigbo, Published @ 2014 by NOBIGDEAL(Ipietoon)