BRAINBIT INFOTECH · RANCHI
COMPLETE JAVASCRIPT COURSE · PART 2 OF 4

Data & the DOM

Store data in arrays and objects, then control the web page: change it, listen to clicks, check forms and build lists.

6 modules~20 hours30 practice examplesNeeds Part 1

By the end of this part you can build

  • Marksheets and product filters with map / filter / reduce
  • A dark-mode switch, counters and tabs
  • A sign-up form with live validation
  • Product lists and search built from data

Every example opens in a live browser preview. Click ✎ Edit on any preview, or press L, to open the Code Lab.

ROADMAP FOR THIS PART

Module 7Arrays & Array Methods3.5 h
Module 8Objects & JSON3 h
Module 9The DOM: Select & Change the Page3.5 h
Module 10Events: Make Pages Interactive3.5 h
Module 11Forms & Validation with JS3 h
Module 12Creating Elements & Rendering Lists3.5 h
JavaScriptBefore we begin

How to Use This Part

Suggested teaching hours per module (Part 2)012343.5 hM73 hM83.5 hM93.5 hM103 hM113.5 hM12

Every module has

  1. 1
    A "Where is it used?" diagram of a real web page
  2. 2
    Concept slides with code + live preview + console
  3. 3
    Step-through animations: watch variables change
  4. 4
    A Live Lab: edit code, see the result instantly
  5. 5
    5 practice examples with solutions
  6. 6
    An animated recap + quiz
Controls→ next, ← back, M menu, L Code Lab, F fullscreen. Click ✎ Edit on any preview to change its code.
MODULE 7

Arrays & Array Methods

⏱ 3.5 hours5 practice examplesLive code lab

You will learn

  • Arrays: lists of values with index positions
  • Add/remove: push, pop, shift, unshift, splice
  • Search: includes, indexOf, find
  • Transform: map, filter, reduce, sort
  • forEach, spread [...] and real data patterns

You will build

  • A marksheet with total, average and toppers
  • A product filter (price, category)
  • A shopping cart total
[]1200450180219993.map().filter().reduce()
Module 7Real-world use

Where Is This Used in Real Websites and Apps?

LOGOCards / boxesListTableNavigation menu

You will find it here

  • Product lists on Amazon / Flipkart are arrays of products
  • Chat messages, notifications, comments: arrays
  • Filters: "under Rs. 500", "4 stars and up" use filter()
  • Totals in a cart use reduce()
  • Sorting: price low to high uses sort()
Module 7Arrays

An Array Is a List in One Variable

const
citiesone name
= [square brackets
"Ranchi", "Dhanbad", "Bokaro"items separated by commas
];
script.jsJS
D:/js-practice/script.js
Console output appears here
"Ranchi"[0]"Dhanbad"[1]"Bokaro"[2]citiesindex starts at 0; length = 3
Why arrays?Instead of city1, city2, city3 ... one array holds 3 or 3,000 items, and a loop can process all of them.
Module 7Add & remove

Adding and Removing Items

script.jsJS
Press Next step to run the program one line at a time.

Memory (variables)

(empty)

Console output

Module 7Searching

Searching an Array: includes, indexOf, find

script.jsJS
D:/js-practice/script.js
Console output appears here
MethodReturns
includes(x)true / false
indexOf(x)position, or -1
find(fn)first item that passes
some / everytrue / false
Module 7Loops over arrays

forEach: Do Something With Each Item

script.jsJS
D:/js-practice/script.js
Console output appears here
D:/js-practice/toppers.html
Console output appears here
CallbackThe arrow function you give to forEach is a callback: forEach calls it once for every item.
Module 7Array methods

Watch map, filter, find, reduce and sort Work

prices
120
450
80
1999
250
Click a method above
result
The big threemap = change every item, filter = keep some items, reduce = combine into one value. None of them change the original array.
Module 7map / filter / reduce

map, filter and reduce in Real Code

script.jsJS
D:/js-practice/script.js
Console output appears here
Objects inside arrays{ name: ..., price: ... } is an object – the next module explains them. Real app data is almost always an array of objects.
Module 7Sorting

Sorting Correctly (Numbers Are Tricky!)

script.jsJS
D:/js-practice/script.js
Console output appears here
Two traps1) sort() without a function compares as TEXT. 2) sort() changes the original array; copy first with [...arr] (spread) if you need the original.
Price: Low to HighThis is exactly what the sort dropdown on shopping sites does.
Module 7More tools

join, slice, spread, includes: Handy Tools

script.jsJS
D:/js-practice/script.js
Console output appears here
MethodUse for
join()array → text (tags, CSV)
slice(a, b)take a part (top 3, page 2)
[...a, ...b]merge or copy
Array.frommake number lists
Module 7Live Lab

Live Lab: Analyse a List of Marks

marks.html – edit me!
Live preview
TryAdd more marks. Show only the top 3 with slice. Count distinctions with filter. Add 5 grace marks to everyone with map.
Module 7Practice Example 1 of 5

Class Marksheet Summary

BeginnerA teacher has the Maths marks of 8 students. Show total, average, highest, lowest and pass count.

Your tasks

  1. Array of 8 marks
  2. Total with reduce
  3. Highest/lowest with Math.max(...marks)
  4. Pass count with filter
  5. Show a summary card on the page
HintMath.max(...marks): the spread operator passes every item as a separate argument.
Where this is used: School ERPs, analytics dashboards, report generators.
marksheet.htmlHTML
Module 7Practice Example 2 of 5

To-Do List Array Operations

BeginnerBefore building the To-Do app UI (Module 12), practise the array logic behind it.

Your tasks

  1. Start with 3 tasks
  2. push a new task
  3. Mark a task done by removing it with splice (find its index with indexOf)
  4. Check includes before adding a duplicate
  5. Print the list as numbered lines with forEach
Where this is used: To-do apps, playlists, carts: add, remove, check duplicates.
todo-logic.jsJS
Module 7Practice Example 3 of 5

Product Price Filter

IntermediateA handicraft store page has a "Max price" slider. Show only products under that price, sorted low to high.

Your tasks

  1. Array of 6 products (name, price)
  2. Range input 100-3000
  3. On input: filter by price, sort, map to HTML
  4. Show "N products found"
  5. Use the same render function on page load
Where this is used: Price filters, search results, category pages.
filter.htmlHTML
Module 7Practice Example 4 of 5

Shopping Cart Total

IntermediateCalculate a cart: each item has price and quantity. Show line totals, subtotal, GST and the grand total.

Your tasks

  1. Array of objects: {name, price, qty}
  2. map to line totals
  3. reduce to subtotal
  4. GST 5%, delivery free above Rs. 499
  5. Print a neat receipt with padEnd
Where this is used: Every checkout page and billing (POS) system.
cart.jsJS
Module 7Practice Example 5 of 5

Leaderboard: Top 3 Quiz Scores

AdvancedAn online quiz for Jharkhand Day shows the top 3 players with medals and the average score.

Your tasks

  1. Array of {player, score}
  2. Copy and sort by score high to low
  3. slice(0, 3) for the top 3
  4. map to HTML with medals 🥇 🥈 🥉
  5. Show the class average and who is above it
Where this is used: Game leaderboards, sales rankings, top products.
leaderboard.htmlHTML
Module 7Module complete

Recap: What You Completed in Module 7

  • ✓Arrays: [ ], index, length
  • ✓push, pop, shift, unshift, splice
  • ✓includes, indexOf, find, some, every
  • ✓forEach and callbacks
  • ✓map (change all), filter (keep some), reduce (combine)
  • ✓sort with (a, b) => a - b; copy with [...arr]
  • ✓join, slice, spread for real data
100%Module 7 done

Coming next

Module 8: Objects & JSON – describe a student, a product or a user with properties.

Quick quiz – click an answer

Q1. Which method makes a NEW array with every item changed?

map returns a new array of the same length.

Q2. [5, 12, 8].filter(n => n > 6) gives:

filter keeps items that pass the test.

Q3. [10, 9, 100].sort() gives:

Without a compare function, numbers are sorted as text.
MODULE 8

Objects & JSON

⏱ 3 hours5 practice examplesLive code lab

You will learn

  • Objects: key-value pairs that describe one thing
  • Reading and changing properties (dot and [ ])
  • Methods and the this keyword
  • Arrays of objects, loops with Object.keys / entries
  • Destructuring, spread and JSON (how apps send data)

You will build

  • A student profile card from an object
  • A product catalogue from an array of objects
  • A settings object saved as JSON
{}name: "Riya"class: 10city: "Ranchi"marks: [92, 88]
Module 8Real-world use

Where Is This Used in Real Websites and Apps?

LOGOCards / boxesFormHeaderTable

You will find it here

  • User profile: { name, email, photo, isPremium }
  • Product: { id, name, price, rating, image }
  • Order: { orderId, items: [...], total, status }
  • API data from servers always arrives as JSON objects
  • An app screen = objects rendered as HTML
Module 8Objects

An Object Describes ONE Thing with Properties

const student = {
name:key
"Riya",value
marks: 92key: value
}
script.jsJS
D:/js-practice/script.js
Console output appears here
ArrayObject
A list of many thingsDetails of one thing
[ ], accessed by index{ }, accessed by key name
marks[0]student.name
Order mattersKeys have names, order rarely matters
Real dataA WhatsApp message is an object: { from, text, time, read }. The chat is an array of these objects.
Module 8Change objects

Add, Change and Delete Properties

script.jsJS
Press Next step to run the program one line at a time.

Memory (variables)

(empty)

Console output

Module 8Methods

Methods and this: Objects That Can Do Things

script.jsJS
D:/js-practice/script.js
Console output appears here
thisInside a method, this means "the object that owns this method". account.deposit() → this = account.
You already use methodsconsole.log, "abc".toUpperCase(), arr.push() are all methods on objects.
Module 8Looping objects

Looping Through an Object: keys, values, entries

script.jsJS
D:/js-practice/script.js
Console output appears here
MethodGives
Object.keys(o)array of keys
Object.values(o)array of values
Object.entries(o)array of [key, value] pairs
for (k in o)each key
Module 8Arrays of objects

Arrays of Objects: The Shape of Real App Data

orders.jsJS
D:/js-practice/orders.js
Console output appears here
Patternarray of objects + filter / map / reduce = most of the logic in dashboards and shops.
Module 8Destructuring

Destructuring and Spread: Modern Shortcuts

script.jsJS
D:/js-practice/script.js
Console output appears here
Where you will see itReact code is full of const { name, price } = props and { ...state, count: 1 }.
Module 8JSON

JSON: How Apps Send and Save Data

JS object{ name: "Riya" } JSON.stringify() JSON.parse() JSON text'{"name":"Riya"}' Text can travel over the internet and be saved in files / localStorage.
script.jsJS
D:/js-practice/script.js
Console output appears here
JSON rule
Keys in double quotes{"name": "Riya"}
Strings in double quotes onlyno single quotes
No functions, no commentsdata only
No trailing commas[1, 2,] is invalid
Module 8Live Lab

Live Lab: Render a Card from an Object

profile.html – edit me!
Live preview
TryChange the object values and watch the card update. Add a isOnline property and show a green dot when true. Make an array of 2 users and render both.
Module 8Practice Example 1 of 5

Student Profile Card from an Object

BeginnerThe school app stores each student as an object. Render one as a profile card.

Your tasks

  1. Object with name, class, section, rollNo, house, photo
  2. Destructure the properties
  3. Build the card HTML with a template literal
  4. Show the house in a coloured badge
  5. Log Object.keys(student)
Hintclass is a reserved word, so read it with student.class instead of destructuring.
Where this is used: Profile pages, ID cards, contact cards.
student.htmlHTML
Module 8Practice Example 2 of 5

Product Catalogue from an Array of Objects

IntermediateShow the Jharkhand Handicrafts catalogue: each product is an object with name, price, image and rating.

Your tasks

  1. Array of 4 product objects
  2. map each product to a card HTML string, join them
  3. Show stars with "★".repeat(Math.round(rating))
  4. Show the cheapest product name using reduce or sort
  5. Grid layout with CSS
Where this is used: Every e-commerce listing page.
catalogue.htmlHTML
Module 8Practice Example 3 of 5

Bank Account Object with Methods

IntermediateModel a savings account for a Ranchi bank app with deposit, withdraw and a mini statement.

Your tasks

  1. Object with holder, balance and transactions: []
  2. deposit(amount) and withdraw(amount) methods using this
  3. Each transaction is pushed as an object {type, amount, balance}
  4. Refuse withdrawals above the balance
  5. Print the statement with console.table
Where this is used: Banking, wallets, games (player.health, player.attack()).
bank.jsJS
Module 8Practice Example 4 of 5

Group Students by City

AdvancedFor school bus planning, group students by city and count them.

Your tasks

  1. Array of student objects with name and city
  2. Build an object like { Ranchi: [...], Khunti: [...] }
  3. Use a loop or reduce; create the key if missing
  4. Print each city with its count using Object.entries
  5. Find the city with the most students
Where this is used: Reports, charts data, grouping orders by status or date.
group.jsJS
Module 8Practice Example 5 of 5

Settings Saved as JSON

IntermediateA news app has settings (theme, font size, language). Convert them to JSON text and back, and apply them to the page.

Your tasks

  1. settings object: theme, fontSize, language
  2. JSON.stringify with indentation (obj, null, 2) shown in a <pre>
  3. JSON.parse the text back
  4. Apply theme and fontSize to document.body.style
  5. Use spread to change one setting
HintIn Module 14 you will save this JSON text in localStorage so it survives a page refresh.
Where this is used: App settings, saving data, sending data to servers.
settings.htmlHTML
Module 8Module complete

Recap: What You Completed in Module 8

  • ✓Objects: { key: value } for one thing
  • ✓Dot and bracket access; add, change, delete
  • ✓Methods and this
  • ✓Object.keys, values, entries; for...in
  • ✓Arrays of objects with filter / map / reduce
  • ✓Destructuring and object spread
  • ✓JSON.stringify and JSON.parse
100%Module 8 done

Coming next

Module 9: The DOM – use JavaScript to find and change any part of a web page.

Quick quiz – click an answer

Q1. How do you read the city of const u = {city: "Ranchi"}?

Dot notation, or u["city"].

Q2. JSON.stringify turns an object into:

JSON is text.

Q3. Inside a method, this refers to:

this = the object before the dot.
MODULE 9

The DOM: Select & Change the Page

⏱ 3.5 hours5 practice examplesLive code lab

You will learn

  • What the DOM is: the page as a tree of objects
  • Selecting: getElementById, querySelector, querySelectorAll
  • Changing text and HTML: textContent, innerHTML
  • Changing styles and classes: style, classList
  • Attributes, images, links and walking the tree

You will build

  • A dark-mode switch
  • An image gallery viewer
  • A "read more" toggle and a live price update
documenthtmlheadbodytitleh1#titleul.menubuttonlili
Module 9Real-world use

Where Is This Used in Real Websites and Apps?

LOGOWhole pageButton

You will find it here

  • Every interactive website changes the DOM: show messages, update counts, hide menus
  • Dark mode: add a class to body
  • Image sliders: change an img src
  • Form errors: show red text under a box
  • Frameworks like React update the DOM for you, but it is still the DOM underneath
Module 9What is the DOM?

DOM = Document Object Model: the Page as a Tree

documenthtmlheadbodytitleh1#titleul.menubuttonlili
  • The browser reads your HTML and builds a tree of objects
  • Each tag becomes a node (an object) you can read and change with JS
  • document is the top of the tree – your entry point
  • Change the DOM → the page on screen updates instantly
HTML file vs DOMJS changes the DOM in memory, not your .html file. Refresh the page and the original HTML comes back.
Module 9Selecting

Selecting Elements: Find Before You Change

Click to run on the page
The code you run appears here.
CSS selectors!querySelector uses the same selectors you learnt in CSS: #id, .class, ul li, :last-child.
D:/js-practice/menu.html
Console output appears here
Module 9Selecting

Which Selector Method Should I Use?

MethodReturnsExampleUse when
getElementById("x")one element or nullgetElementById("cart")Element has an id (fastest)
querySelector(css)FIRST match or nullquerySelector(".price")Any CSS selector, one element
querySelectorAll(css)NodeList (all matches)querySelectorAll(".card")Many elements; loop with forEach
getElementsByClassNamelive HTMLCollection(older style)You will see it in old code
null errorsIf nothing matches, you get null. Then null.textContent throws TypeError: Cannot read properties of null. Check the spelling of the id/class, and that the script runs after the HTML.
Store it in a variableconst btn = document.querySelector("#orderBtn"); – then use btn many times instead of searching again.
Module 9Changing

Changing Text, HTML, Styles and Classes

Click to run on the page
The code you run appears here.
innerHTML and safetyNever put text typed by users into innerHTML: it could contain harmful HTML/script. Use textContent for user text.
D:/js-practice/order.html
Console output appears here
Module 9classList

classList: The Best Way to Change Styles

MethodDoes
el.classList.add("x")add a class
el.classList.remove("x")remove it
el.classList.toggle("x")add if missing, remove if present
el.classList.contains("x")true / false
Why classes, not style?Keep the design in CSS (.dark { ... }) and let JS only switch classes on/off. Cleaner code, and designers can change the look without touching JS.
D:/js-practice/dark-mode.html
Console output appears here
Module 9Walking the tree

Parents, Children and Siblings

page.htmlHTML
D:/js-practice/page.html
Console output appears here
closest()el.closest(".card") finds the nearest parent matching a selector. Very useful with buttons inside cards (Module 10).
Module 9Live Lab

Live Lab: Change the Page with JS

dom-lab.html – edit me!
Live preview
TryChange the image to images/netarhat.jpg and the title to match. Change the button text to "Show less" when open. Add a class instead of setting style.color.
Module 9Practice Example 1 of 5

Dark Mode Switch

BeginnerThe BrainBit Infotech blog wants a dark mode switch that also updates the button text.

Your tasks

  1. CSS: body.dark styles for background and text
  2. Button with id "mode"
  3. On click: document.body.classList.toggle("dark")
  4. Change the button text using contains("dark")
  5. Log the current mode
Where this is used: YouTube, WhatsApp Web, news sites, every modern app.
dark.htmlHTML
Module 9Practice Example 2 of 5

Image Gallery Viewer

BeginnerA tourism page shows one big photo and small thumbnails. Clicking a thumbnail changes the big photo and the caption.

Your tasks

  1. One big <img id="main"> and a caption
  2. 4 thumbnails with onclick="show(this)"
  3. show(img) copies img.src and img.alt to the main image
  4. Highlight the active thumbnail with a class
  5. Log which photo was chosen
Where this is used: Product photo galleries on Amazon/Flipkart, property listings.
gallery.htmlHTML
Module 9Practice Example 3 of 5

Read More / Read Less Toggle

BeginnerA news article shows only a short preview. "Read more" reveals the rest and the button changes to "Read less".

Your tasks

  1. Hidden paragraph with class "more" (display: none)
  2. Button toggles a class "open" on the article
  3. CSS shows .more when the article has .open
  4. Button text changes with a ternary
  5. Use querySelector inside the article
Where this is used: News, product descriptions, reviews, FAQ answers.
read-more.htmlHTML
Module 9Practice Example 4 of 5

Live Price Update with Quantity

IntermediateA product page shows price per item. When the user changes quantity, the total updates immediately.

Your tasks

  1. Product name, unit price (data attribute), quantity input
  2. Read dataset.price from the element
  3. On input, calculate and show total with toLocaleString("en-IN")
  4. Show "Free delivery" when total is 499 or more (classList)
  5. Do not allow quantity below 1
Hintdata-price="199" on HTML is read in JS as element.dataset.price (a string).
Where this is used: Product pages, carts, booking forms (tickets x price).
price.htmlHTML
Module 9Practice Example 5 of 5

Highlight Search Matches in a Table

IntermediateA school contact list: typing in a search box highlights matching rows and hides the others.

Your tasks

  1. Table of 6 teachers (name, subject, phone)
  2. Search input with id "q"
  3. querySelectorAll("tbody tr") and loop
  4. Hide non-matching rows with style.display, highlight matches with a class
  5. Show "N results"
Where this is used: Admin tables, contact lists, search-as-you-type.
search-table.htmlHTML
Module 9Module complete

Recap: What You Completed in Module 9

  • ✓DOM = the page as a tree of objects
  • ✓getElementById, querySelector, querySelectorAll
  • ✓null when nothing matches (common error)
  • ✓textContent vs innerHTML (safety)
  • ✓style for one property; classList for design
  • ✓Attributes, src, alt, dataset
  • ✓parentElement, children, siblings, closest
100%Module 9 done

Coming next

Module 10: Events – respond to clicks, typing, keys and scrolling.

Quick quiz – click an answer

Q1. Which selects ALL elements with class "card"?

querySelectorAll returns every match.

Q2. Safest way to show user-typed text?

textContent never runs HTML.

Q3. Best way to switch dark mode?

Design stays in CSS; JS just toggles a class.
MODULE 10

Events: Make Pages Interactive

⏱ 3.5 hours5 practice examplesLive code lab

You will learn

  • What events are: click, input, keydown, submit, scroll...
  • addEventListener and the event object
  • Mouse, keyboard, form and window events
  • Event bubbling and event delegation
  • preventDefault and removing listeners

You will build

  • A like counter and a quantity stepper
  • Tabs and an accordion with JS
  • Keyboard shortcuts and a character counter
Click meaddEventListener
Module 10Real-world use

Where Is This Used in Real Websites and Apps?

LOGOButtonFormNavigation menuCards / boxes

You will find it here

  • click: buttons, menus, like hearts, add to cart
  • input: live search, character counters, price sliders
  • submit: forms (Module 11)
  • keydown: shortcuts, games, chat "Enter to send"
  • scroll: sticky headers, "back to top", infinite feeds
Module 10Events

Events: The Page Listens, Your Code Responds

1. User actsclicks a buttonthe EVENT happens2. Browser tells JS"click" on #likeBtnevent object created3. Your function runslikes++the page updatesbutton.addEventListener("click", function () { ... })
btnelement
.addEventListener(
"click"event name
, handlerfunction to run
)
WayExampleUse?
HTML attributeonclick="like()"quick demos
Propertybtn.onclick = likeonly one handler
addEventListenerbtn.addEventListener("click", like)best: many handlers, more control
Module 10First listener

Your First Event Listener: a Like Button

page.htmlHTML
D:/js-practice/page.html
Console output appears here
Module 10Event types

Event Types Playground: Watch the Console

D:/js-practice/events.html
Console output appears here
EventFires when
click / dblclickclicked / double-clicked
mouseenter / mouseleavemouse moves in / out
inputevery change while typing
changevalue committed (select, checkbox)
keydowna key is pressed
focus / blurbox selected / left
submita form is sent
scroll, resize, loadwindow events
Try itMove the mouse over the box, click it, type in the input, change the city.
Module 10Event object

The Event Object: Details About What Happened

page.htmlHTML
D:/js-practice/page.html
Console output appears here
PropertyGives
e.targetthe element that was clicked/typed in
e.type"click", "keydown"...
e.keykey pressed: "Enter", "a", "ArrowUp"
e.target.valuetext in an input
Module 10Bubbling

Event Bubbling: Events Travel Upwards

document / body div.card div.actions button click 1. starts at the button2. bubbles to .actions 3. then to .card4. then body, document
page.htmlHTML
D:/js-practice/page.html
Console output appears here
Stop ite.stopPropagation() stops the bubble. Needed rarely, for example a button inside a clickable card.
Module 10Delegation

Event Delegation: One Listener for Many Buttons

page.htmlHTML
D:/js-practice/page.html
Console output appears here
Why delegation?Items added later (from data, from an API) automatically work, and 1 listener is faster than 100. Real carts, to-do lists and chat apps use this.
Module 10preventDefault

preventDefault: Stop the Browser's Default Action

page.htmlHTML
D:/js-practice/page.html
Console output appears here
ElementDefault action
link <a>opens the URL
<form> submitreloads / goes to action URL
right-clickcontext menu
checkboxtoggles
Single-page appsAlmost every modern form handler starts with e.preventDefault() and sends the data with JavaScript (Module 16).
Module 10Live Lab

Live Lab: A Quantity Stepper

stepper.html – edit me!
Live preview
TryLimit the maximum to 10. Make the + and - keys on the keyboard work (listen for keydown on document). Disable the minus button at 1.
Module 10Practice Example 1 of 5

Character Counter for a Feedback Box

BeginnerLike Twitter/X, a feedback box allows 150 characters and shows how many are left.

Your tasks

  1. textarea with maxlength 150
  2. Listen to the input event
  3. Show "N characters left"
  4. Turn the counter red when fewer than 20 remain
  5. Disable the Send button when the box is empty
Where this is used: Comment boxes, SMS composers, bio fields.
counter.htmlHTML
Module 10Practice Example 2 of 5

Tabs with JavaScript

IntermediateA course page has 3 tabs: Overview, Syllabus, Fees. Clicking a tab shows its panel.

Your tasks

  1. Buttons with data-tab="overview" etc.
  2. Panels with matching ids
  3. One listener on the tab bar (delegation)
  4. Remove "active" from all, add to the clicked tab and its panel
  5. Log which tab is open
Where this is used: Product pages, settings, dashboards.
tabs.htmlHTML
Module 10Practice Example 3 of 5

FAQ Accordion (Only One Open)

IntermediateAn FAQ where opening one answer closes the others.

Your tasks

  1. Questions are buttons, answers are divs after them
  2. Listener on the FAQ container
  3. On click: close all answers, then open the clicked one (unless it was already open)
  4. Rotate a + icon with a class
  5. Use nextElementSibling
Where this is used: FAQ sections, mobile menus, filters.
faq.htmlHTML
Module 10Practice Example 4 of 5

Keyboard Shortcuts and Arrow-Key Movement

IntermediateA simple game board: move a car with arrow keys; press R to reset. (Click the preview first so it gets the key presses.)

Your tasks

  1. Listen to keydown on document
  2. switch on e.key: ArrowUp/Down/Left/Right change x and y
  3. Keep the car inside the board (min/max)
  4. Move with style.transform
  5. "r" resets; prevent the page from scrolling with preventDefault
Where this is used: Games, slideshow navigation, editor shortcuts (Ctrl+S).
keys.htmlHTML
Module 10Practice Example 5 of 5

Back-to-Top Button on Scroll

AdvancedA long article page shows a "Back to top" button only after scrolling 200px, plus a reading progress bar.

Your tasks

  1. Long content, a fixed button (hidden at first)
  2. Listen to scroll on window
  3. Show the button when scrollY > 200
  4. Progress bar width = scrolled / (total - window height) * 100%
  5. Button click: window.scrollTo({ top: 0, behavior: "smooth" })
Where this is used: Blogs, news, long documentation pages.
scroll.htmlHTML
Module 10Module complete

Recap: What You Completed in Module 10

  • ✓Events: user actions the browser reports
  • ✓addEventListener(type, handler)
  • ✓click, input, change, keydown, focus/blur, submit, scroll
  • ✓The event object: target, type, key, value
  • ✓Bubbling: events travel up to parents
  • ✓Delegation: one listener on the parent + closest()
  • ✓preventDefault for links and forms
100%Module 10 done

Coming next

Module 11: Forms & Validation with JS – check data before it is sent.

Quick quiz – click an answer

Q1. Which event fires on every keystroke in an input?

input fires on every change.

Q2. e.target is:

target = where it happened.

Q3. Stop a form from reloading the page:

preventDefault cancels the default action.
MODULE 11

Forms & Validation with JS

⏱ 3 hours5 practice examplesLive code lab

You will learn

  • Reading values: text, number, checkbox, radio, select
  • The submit event and preventDefault
  • Showing error messages under each field
  • Live validation while typing
  • Regular expressions (regex) for mobile, email, PIN

You will build

  • A sign-up form with live errors
  • A password strength meter
  • A loan eligibility form
Enter a 10-digit mobileRegister
Module 11Real-world use

Where Is This Used in Real Websites and Apps?

LOGOFormButton

You will find it here

  • Sign-up and login pages check fields before sending
  • Checkout: address, PIN code, mobile
  • Exam / job applications on government portals
  • Instant feedback: "Password too weak", "Email already used"
  • JS validation is for user comfort; servers must validate again
Module 11Reading values

Reading Every Kind of Form Field

D:/js-practice/read.html
Console output appears here
FieldRead with
text, email, numberinput.value (always a string)
number as numberNumber(input.value) or input.valueAsNumber
checkboxinput.checked (true/false)
radio groupform.querySelector("[name=batch]:checked").value
selectselect.value
whole formnew FormData(form)
form.fieldNameInside a form, form.name, form.age give the field with that name attribute.
Module 11Validation flow

The Validation Flow Every Form Uses

submituser clicks RegisterpreventDefaultstop page reloadcheck each fieldcollect errorserrors?decide YES: show messagesred borders, focus first error NO:send
1

HTML validation

required, type="email", pattern: quick, built in (Part 1 of HTML course).
2

JS validation

Custom rules and custom messages: "Mobile must start with 6-9", passwords match, age 18+.
3

Server validation

ALWAYS needed: anyone can bypass the browser. JS is for a better user experience.
Module 11Submit validation

Validate on Submit and Show Errors Under Fields

D:/js-practice/register.html
Console output appears here
Try itClick Register with empty boxes, then type "Ri" and "12345", then a real-looking name and 9876543210.
register.jsJS
novalidateThe novalidate attribute turns off the browser bubbles so your own messages show instead.
Module 11Regex

Regular Expressions: Patterns for Text

/start
^start of text
[6-9]one digit 6 to 9
\d{9}then exactly 9 digits
$end of text
/end
script.jsJS
D:/js-practice/script.js
Console output appears here
PatternMeans
\dany digit 0-9
[a-z]one letter a to z
{6} / {2,4}exactly 6 / between 2 and 4
+ / *one or more / zero or more
^ ... $the WHOLE text must match
\sa space
/i /gignore case / all matches
Do not memoriseProfessionals copy tested patterns (mobile, email, PIN) and test them on regex101.com.
Module 11Live validation

Live Validation While Typing: Password Strength

D:/js-practice/password.html
Type a passwordTry: ranchi → ranchi2026 → Ranchi2026 → Ranchi@2026
password.jsJS
input vs submitLive (input event) checks feel friendly; final (submit) checks are the safety net. Good forms use both.
Module 11Live Lab

Live Lab: PIN Code Delivery Checker

pincode.html – edit me!
Live preview
TryTest 834001 (Ranchi), 12345, 800001. Add Bokaro (827001). Show the city name using an object { "834001": "Ranchi", ... } instead of an array.
Module 11Practice Example 1 of 5

Sign-Up Form with Error Messages

IntermediateBrainBit Infotech app sign-up: name, email, mobile, password, confirm password. Show an error under each wrong field.

Your tasks

  1. novalidate form + submit listener with preventDefault
  2. Helper setError(field, message)
  3. Rules: name 3+, email regex, mobile regex, password 8+, passwords match
  4. Red/green borders with classes
  5. On success show "Account created for NAME"
Where this is used: Every sign-up page.
signup.htmlHTML
Module 11Practice Example 2 of 5

Live Email Availability Check

BeginnerWhile typing an email, show a green tick if the format is valid and the email is not already taken.

Your tasks

  1. Array of taken emails
  2. input event on the email field
  3. Check format with regex first
  4. Then check includes (lowercase)
  5. Messages: invalid format / already registered / available
HintReal apps ask the server "is this email taken?" using fetch (Module 16). The logic is the same.
Where this is used: Username / email availability on sign-up pages.
email-check.htmlHTML
Module 11Practice Example 3 of 5

Password Strength Meter

IntermediateBuild your own password strength meter with a coloured bar and a show/hide eye button.

Your tasks

  1. 4 rules with regex: length 8+, digit, capital, symbol
  2. Score 0-4 drives bar width and colour
  3. Label: Weak / Fair / Good / Strong
  4. Eye button toggles input type between password and text
  5. Disable the Save button until score is at least 3
Where this is used: Account creation and password change pages.
strength.htmlHTML
Module 11Practice Example 4 of 5

Loan Eligibility Form

IntermediateA Jharkhand gramin bank form: age, monthly income, existing EMI and loan amount. Decide eligibility and the max loan.

Your tasks

  1. Read numbers with Number()
  2. Rules: age 21-60, income at least Rs. 15,000
  3. Max EMI allowed = 50% of income minus existing EMI
  4. Max loan = max EMI x 36
  5. Show approved / rejected with the reasons list
Where this is used: Bank, insurance and government scheme eligibility checkers.
loan.htmlHTML
Module 11Practice Example 5 of 5

Multi-Step Admission Form

AdvancedSplit a long admission form into 3 steps with Next/Back buttons. A step cannot be left until its fields are valid.

Your tasks

  1. 3 fieldsets, only one visible (class "active")
  2. Progress text "Step 1 of 3"
  3. Next validates the current step's required inputs with checkValidity()
  4. Back goes to the previous step
  5. Final step shows a summary from FormData
Where this is used: Exam registrations, insurance quotes, checkout flows.
multistep.htmlHTML
Module 11Module complete

Recap: What You Completed in Module 11

  • ✓Read text, number, checkbox, radio, select values
  • ✓FormData for the whole form
  • ✓submit + preventDefault + check fields
  • ✓Show errors under each field with classes
  • ✓novalidate to use your own messages
  • ✓Regex: test() for mobile, PIN, email
  • ✓Live validation with the input event
100%Module 11 done

Coming next

Module 12: Creating Elements & Rendering Lists – build the page from data.

Quick quiz – click an answer

Q1. A checkbox is ticked when:

Use .checked for checkboxes and radios.

Q2. /^\d{6}$/ matches:

Exactly 6 digits, nothing else.

Q3. Is JavaScript validation enough for security?

Users can bypass anything in the browser.
MODULE 12

Creating Elements & Rendering Lists

⏱ 3.5 hours5 practice examplesLive code lab

You will learn

  • createElement, append, prepend, remove
  • innerHTML vs createElement: when to use which
  • Rendering a list from an array (data → screen)
  • The render() pattern: change data, then redraw
  • Search, filter and sort a rendered list

You will build

  • A dynamic to-do list
  • A product grid with category filter
  • A searchable contact book
data.map(item => card)
Module 12Real-world use

Where Is This Used in Real Websites and Apps?

LOGOCards / boxesListTable

You will find it here

  • Feeds: Instagram posts, YouTube videos, news items
  • Product grids built from an array of products
  • Chat messages added at the bottom as they arrive
  • Search results that update as you type
  • This is exactly what React, Vue and Angular automate
Module 12Creating elements

Create, Add and Remove Elements

Click to run on the page
The code you run appears here.
MethodDoes
createElement("li")makes a new element (not on page yet)
parent.append(el)adds at the end
parent.prepend(el)adds at the start
el.remove()deletes it
D:/js-practice/notices.html
Console output appears here
Module 12Two ways

createElement vs innerHTML: Which One?

two-ways.jsJS
createElementinnerHTML template
Code lengthlongershort
Safe with user text?yes (textContent)no, unless escaped
Keeps existing listeners?yesno (rebuilds everything)
Best foradding one item, user contentrendering a whole list from your data
Rule of thumbYour own data (products, menu) → template + innerHTML. Anything the user typed → textContent.
Module 12Render pattern

The Render Pattern: Data First, Then Draw

DATAlet todos = [...] render()data -> HTML SCREENwhat the user sees user clicks: change the DATA, then call render() again The render pattern (the idea behind React)
1

1. Keep data in an array

The array is the "single source of truth".
2

2. One render() function

Clears the list and draws every item from the array.
3

3. Never edit the screen directly

Change the array (push, filter, sort), then call render().
Module 12Render pattern

The Render Pattern in Action: a Mini To-Do

D:/js-practice/todo.html
Console output appears here
Try itAdd tasks, click a task to mark it done, click × to delete. Watch the data array in the console.
todo.jsJS
Module 12Filter + render

Search, Filter and Sort a Product Grid

D:/js-practice/shop.html
Console output appears here
  1. 1
    All products stay in products (never changed)
  2. 2
    render() reads the search box, category and sort
  3. 3
    filter for search + category
  4. 4
    sort for price order
  5. 5
    map to HTML, join, put into the grid
  6. 6
    Every control calls the same render()
This is a real shop pageAmazon, Flipkart and Meesho category pages work on this same idea (with data from a server).
Module 12Live Lab

Live Lab: A Chat Window

chat.html – edit me!
Live preview
TrySend messages. Make Riya auto-reply "OK!" 1 second later with setTimeout (preview of Module 13). Show the time under each message.
Module 12Practice Example 1 of 5

Dynamic To-Do List

BeginnerBuild a to-do list with add, complete and delete, using the render pattern.

Your tasks

  1. Data: array of {text, done}
  2. Add with button and Enter key
  3. Click text to toggle done
  4. × button deletes (delegation with data-index)
  5. Show "N of M done" and an empty message
HintIn Module 14 you will save todos in localStorage so tasks survive a refresh.
Where this is used: Task apps, shopping lists, notes apps.
todo.htmlHTML
Module 12Practice Example 2 of 5

Render a Results Table from Data

BeginnerBuild the JAC results table from an array of objects, with a coloured result column and totals.

Your tasks

  1. Array of {name, maths, science, english}
  2. For each student create a <tr> with total and PASS/FAIL
  3. Use createElement for rows, textContent for cells
  4. Colour PASS green and FAIL red with classes
  5. Footer row with class average
Where this is used: Admin panels, reports, school ERP screens.
results.htmlHTML
Module 12Practice Example 3 of 5

Product Grid with Category Buttons

IntermediateA cafe menu page: category buttons (All, Snacks, Drinks, Meals) filter the menu cards.

Your tasks

  1. Menu data with name, price, category, image
  2. Category buttons generated from the data (unique categories with Set)
  3. Clicking a button sets the active category and calls render()
  4. Active button highlighted
  5. Cards appear with a small CSS animation
Hintnew Set(array) removes duplicates: perfect for building a category list from data.
Where this is used: Restaurant menus, e-commerce categories, portfolio filters.
menu.htmlHTML
Module 12Practice Example 4 of 5

Searchable Contact Book

IntermediateA contact book: add contacts (name + phone) and search them live. Avatars show the first letter of the name.

Your tasks

  1. Array of {name, phone}
  2. Add form (prevent default), validate a 10-digit phone
  3. Search box filters by name or phone
  4. Sort contacts alphabetically with localeCompare
  5. Avatar circle with the first letter and a colour
Where this is used: Phone contacts, CRM customer lists, staff directories.
contacts.htmlHTML
Module 12Practice Example 5 of 5

Mini Cart: Add to Cart from a Product List

AdvancedTwo lists on one page: products (with Add buttons) and the cart (with quantities and total). Both are drawn from data.

Your tasks

  1. products array and cart array of {id, qty}
  2. Add button: if the item is already in the cart, qty++ else push
  3. renderCart shows name, qty, line total and grand total
  4. + / - buttons in the cart; remove when qty is 0
  5. Cart badge count in the header
Where this is used: Every shopping cart and food-ordering app.
mini-cart.htmlHTML
Module 12Module complete

Recap: What You Completed in Module 12

  • ✓createElement, append, prepend, remove
  • ✓insertAdjacentHTML and innerHTML templates
  • ✓textContent for user text (safety)
  • ✓Render pattern: data → render() → screen
  • ✓Change data, then re-render
  • ✓Search + filter + sort before rendering
  • ✓Delegation with data-* attributes for item buttons
100%Module 12 done

Coming next

Part 3: Timers, localStorage, async JavaScript and real APIs.

Quick quiz – click an answer

Q1. Which adds an element at the END of a list?

append adds to the end.

Q2. In the render pattern, to delete an item you:

Data is the source of truth.

Q3. [...new Set(["a","b","a"])] gives:

A Set keeps unique values.
PART 2 COMPLETE

Well done!

You have finished Part 2 of the Complete JavaScript Course.

Modules completed

  • Module 7: Arrays & Array Methods
  • Module 8: Objects & JSON
  • Module 9: The DOM: Select & Change the Page
  • Module 10: Events: Make Pages Interactive
  • Module 11: Forms & Validation with JS
  • Module 12: Creating Elements & Rendering Lists

Keep all your practice files in D:\js-practice. You will reuse them in the capstone apps.

</> Code Lab
Edit the code – the preview updates as you type
Live preview