Web Technology IIUnit 79 min read

JavaScript Basics & DOM Manipulation: Syntax, Events, and Dynamic Web Pages

Unit 7 of Web Technology II covers JavaScript fundamentals—variables, loops, functions, and DOM manipulation—explaining how to interact with HTML elements dynamically, handle events, and build responsive web interfaces. Real-world examples from eSewa, Daraz, and Ncell illustrate practical applications.

Core Concepts of JavaScript

What is JavaScript?

JavaScript (JS) is a client-side scripting language embedded in HTML to create dynamic and interactive web pages. Unlike PHP (server-side), JS runs in the user’s browser, enabling real-time updates without page reloads.

classDiagram
    class ClientSide {
        +Runs in browser
        +No server reload needed
        +Examples: Animations, form validation
    }
    class ServerSide {
        +Runs on server (e.g., PHP)
        +Requires page refresh
        +Examples: Database queries
    }
    ClientSide --> "Uses" JavaScript
    ServerSide --> "Uses" PHP

Key Features:

  • Event-driven: Responds to user actions (clicks, keypresses).
  • Asynchronous: Can fetch data without blocking the UI (e.g., AJAX).
  • DOM Integration: Modifies HTML/CSS dynamically.

Variables, Data Types, and Operators

Variables

Variables store data values. Declare them with let, const, or var:

let age = 25;          // Mutable
const PI = 3.14;       // Immutable
var oldSyntax = true;  // Avoid (legacy)

Data Types

JavaScript has primitive (immutable) and reference (mutable) types:

Type Example Description
number 42, 3.14 Integers/floats
string "Hello" Text (use ' or ")
boolean true, false Logical values
undefined let x; Uninitialized variable
null null Intentional empty value
object {name: "Alice"} Key-value pairs (e.g., JSON)
array [1, 2, 3] Ordered list
function function() {} Reusable code blocks

Example: Storing user input from a Daraz order form:

let userName = "Rohan";  // String
let orderTotal = 5000;   // Number
let isPremium = false;   // Boolean

Control Structures: Conditional Logic

if-else Statements

Execute code based on conditions:

let discount = 0;
if (orderTotal > 10000) {
    discount = 10;       // 10% off for orders > Rs. 10,000
} else if (orderTotal > 5000) {
    discount = 5;        // 5% off for orders > Rs. 5,000
} else {
    discount = 0;
}
console.log(`Discount: ${discount}%`);

Ternary Operator

Shortcut for simple conditions:

let message = (isPremium) ? "Free shipping!" : "Shipping fee applies.";

Loops: Iterating Over Data

for Loop

Repeat code a set number of times:

// Display items in a Daraz cart
for (let i = 0; i < cartItems.length; i++) {
    console.log(`Item ${i + 1}: ${cartItems[i].name}`);
}

while Loop

Run while a condition is true:

let attempts = 3;
while (attempts > 0 && !loginSuccess) {
    console.log(`Attempts left: ${attempts}`);
    attempts--;
}

Functions: Reusable Code Blocks

Defining Functions

// Calculate total with discount
function calculateTotal(price, discountPercent) {
    return price * (1 - discountPercent / 100);
}
let finalPrice = calculateTotal(5000, 10); // Rs. 4,500

Arrow Functions (ES6)

Shorthand syntax:

const applyDiscount = (price, discount) => price * (1 - discount);

Example: Ncell’s "Check Balance" button uses JS to fetch and display balance dynamically:

function fetchBalance() {
    // Simulate API call
    let balance = 1200;
    document.getElementById("balance").textContent = `Rs. ${balance}`;
}

The Document Object Model (DOM)

What is the DOM?

The DOM is a tree-like representation of HTML elements. JavaScript can:

  • Access/modify elements (getElementById, querySelector).
  • Change content, styles, or attributes.
  • Handle events (clicks, form submissions).
graph TD
    A["Document"] --> B["HTML Element"]
    B --> C["Attribute"]
    B --> D["Method"]
    B --> E["Property"]
    C --> F["class, id, src"]
    D --> G["click(), addEventListener()"]
    E --> H["innerHTML, style"]

Example: Updating eSewa’s payment status in real-time:

<p id="paymentStatus">Processing...</p>
<script>
    setTimeout(() => {
        document.getElementById("paymentStatus").textContent = "Payment successful!";
    }, 3000);
</script>

DOM Manipulation Techniques

Selecting Elements

Method Example Use Case
getElementById document.getElementById("btn") Target a single element by ID
querySelector document.querySelector(".cart") Target by CSS class/ID
getElementsByClassName document.getElementsByClassName("item") Get all elements with a class

Modifying Elements

// Change text and style
let heading = document.querySelector("h1");
heading.textContent = "Welcome to Daraz!";
heading.style.color = "red";

// Add/remove classes
let button = document.getElementById("submitBtn");
button.classList.add("active");
button.classList.remove("disabled");

Example: Pathao’s ride status updates:

function updateRideStatus(status) {
    let statusElement = document.getElementById("rideStatus");
    statusElement.textContent = status;
    if (status === "Arrived") {
        statusElement.style.color = "green";
    }
}

Event Handling

Common Events

Event Triggered When Example
click User clicks an element Button submissions
submit Form is submitted Login/signup forms
keydown Key is pressed Search input
mouseover Mouse hovers over an element Tooltips

Adding Event Listeners

// Ncell’s "Top Up" button
document.getElementById("topUpBtn").addEventListener("click", function() {
    alert("Top-up successful! Rs. 100 added.");
});

Example: Kathmandu traffic route optimizer (simplified):

document.getElementById("routeBtn").addEventListener("click", () => {
    let route = document.querySelector(".route").textContent;
    if (route === "Heavy Traffic") {
        alert("Take alternative route via Thapathali!");
    }
});

In the Real World

  1. eSewa

    • Idea Used: DOM Manipulation + Event Handling
    • How: Dynamically updates payment status (e.g., "Processing" → "Completed") without refreshing the page. Uses setTimeout and innerHTML to reflect real-time transactions.
  2. Daraz

    • Idea Used: Functions + Loops
    • How: The "Add to Cart" button triggers a function that loops through product arrays to update the cart total. Arrow functions handle discounts dynamically.
  3. Ncell’s MyNcell App

    • Idea Used: Event Listeners + DOM Updates
    • How: The "Check Balance" button uses addEventListener("click") to fetch balance data (simulated via JS) and display it in a <div> without page reload.

Common Pitfalls and Best Practices

Pitfall Solution
Using var instead of let/const Always use let for variables, const for constants.
Not handling errors Wrap API calls in try-catch.
Overusing innerHTML Use textContent to avoid XSS risks.
Memory leaks from event listeners Remove listeners with removeEventListener.

Example: Secure password validation (avoiding innerHTML):

let passwordInput = document.getElementById("password");
passwordInput.addEventListener("input", function() {
    if (this.value.length < 8) {
        this.style.borderColor = "red";
    } else {
        this.style.borderColor = "green";
    }
});

Exam Tip

What to Expect in TU/PU Exams

  1. Short Questions (2–5 marks):

    • Define DOM, event listener, or arrow function.
    • Write a snippet to change text content or add a class.
    • Example Question: "Write JavaScript to hide an element with ID errorMsg when a button is clicked."
  2. Programming Questions (10–15 marks):

    • Trace the output of a given JS loop or function.
    • Debug code with missing semicolons or incorrect selectors.
    • Build a mini-project:
      • Dynamic form validation (e.g., email format check).
      • Simple calculator using onclick events.
    • Example Question: "Write a function calculateTax(income) that returns tax as 10% if income > 500,000, else 0. Use it to display tax for Rs. 600,000."
  3. Application-Based Questions (5–10 marks):

    • Explain how JS is used in eSewa payments or Daraz cart updates.
    • Example Question: "How would you use DOM manipulation to show a loading spinner while fetching data from a server?"

Key Formulas to Remember

  • Discount Calculation: finalPrice = originalPrice * (1 - discountPercent / 100)
  • Loop Iterations: For for (let i = 0; i < n; i++), iterations = n.

Common Exam Traps

  • Off-by-one errors in loops (e.g., i <= n vs i < n).
  • Case sensitivity in IDs/classes (e.g., getElementById("Submit") vs getElementById("submit")).
  • Async confusion: JS is single-threaded; avoid blocking the UI with long loops.

dom tree structure htmlVisual representation of a parsed HTML document (Image: Lubaochuan, CC BY-SA 4.0, via Wikimedia Commons)

Based on the TU BIM syllabus for Web Technology II (IT239), unit 7.

Discussion

Loading…