CSC318 Web Technology

Web TechnologyUnit 515 min read

JavaScript Basics, DOM & Objects: Syntax, Validation, and Dynamic Web Pages

Unit 5 of Web Technology covers JavaScript fundamentals—variables, loops, functions, DOM manipulation (changing HTML/CSS dynamically), and object-oriented programming (classes, prototypes)—with real-world form validation examples and interactive web page techniques.

TAKEAWAYS:

  • JavaScript is the only language that runs natively in browsers, enabling dynamic content, form validation, and user interactions without page reloads.
  • The DOM (Document Object Model) treats HTML as a tree of objects you can modify with JavaScript (e.g., change text, hide/show elements, respond to clicks).
  • Objects in JavaScript are unordered collections of key-value pairs (e.g., {name: "Alice", age: 25}), and classes provide blueprints for creating multiple objects.
  • Form validation with JavaScript improves user experience by catching errors before submission (e.g., checking email format, password strength).
  • Arrays and functions are essential for organizing data and reusing code (e.g., looping through form fields, calculating totals).
  • AJAX (Asynchronous JavaScript) lets web pages fetch data from servers without refreshing (used by eSewa for real-time balance checks).

Core Concepts: JavaScript Basics

JavaScript (JS) is a client-side scripting language that adds interactivity to websites. Unlike HTML (structure) or CSS (style), JS handles behavior.

1. Variables and Data Types

Variables store data. JS is dynamically typed, meaning you don’t declare types explicitly.

NumberStringBooleanArrayObjectVariable
Hierarchy of JavaScript data types (dynamically typed)

Example: Storing User Data

let username = "john_doe";       // String
let age = 25;                    // Number
let isLoggedIn = true;           // Boolean
let hobbies = ["reading", "coding"]; // Array
let user = {                     // Object
    name: "Alice",
    email: "alice@example.com"
};

2. Operators and Expressions

Operators perform operations on variables (e.g., +, -, ==, &&).

Operator Example Description
+ 5 + 3 Addition
== "5" == 5 Loose equality (type-coerced)
=== "5" === 5 Strict equality (no type coercion)
&& true && false Logical AND
! !isLoggedIn Logical NOT

Example: Checking Password Length

let password = "secure123";
let isValid = password.length >= 8; // true

DOM Manipulation: Changing the Web Page Dynamically

The DOM (Document Object Model) represents HTML as a tree of nodes (elements, attributes, text). JS can:

  • Access/modify elements (e.g., change text, styles).
  • Respond to events (e.g., clicks, keypresses).

How to Select and Modify Elements

Method Example Description
document.getElementById() let heading = document.getElementById("title"); Select by ID.
document.querySelector() let button = document.querySelector("button"); Select by CSS selector.
.innerHTML heading.innerHTML = "<b>New Title</b>"; Set HTML content.
.style.property button.style.backgroundColor = "red"; Change CSS properties.
.addEventListener() button.addEventListener("click", myFunction); Attach event handlers.
HTML DocumentStatic ContentDOM TreeLive Object ModelJavaScriptDynamic Modifications
How JavaScript interacts with the DOM

Worked Example: Changing Text on Click

<button id="clickMe">Click Me</button>
<p id="output">Initial text</p>

<script>
  document.getElementById("clickMe").addEventListener("click", function() {
    document.getElementById("output").innerHTML = "Button clicked!";
  });
</script>

Real-World Tie-In: Pathao’s Dynamic Ride Updates Pathao’s app uses DOM manipulation to:

  1. Update the live location of the driver on a map (via setInterval and DOM updates).
  2. Change the ride status (e.g., "Driver arrived" → "On the way") by modifying <div> classes.
  3. Show real-time fare calculations without refreshing the page.

Objects and Classes: Organizing Data

Objects group related data and functions. Classes (ES6+) provide a template for creating objects.

1. Objects (Literal Notation)

let user = {
    name: "Bob",
    age: 30,
    greet: function() {
        return `Hello, ${this.name}!`;
    }
};
console.log(user.greet()); // "Hello, Bob!"

2. Classes (ES6 Syntax)

classDiagram
  class Person {
    +name: string
    +age: number
    +greet(): void
  }
  class Student {
    +grade: string
    +study(): void
  }
  Person <|-- Student
  class Person {
    +constructor(name: string, age: number)
  }
  class Student {
    +constructor(name: string, age: number, grade: string)
  }

Example: Student Class

class Student {
    constructor(name, grade) {
        this.name = name;
        this.grade = grade;
    }
    study() {
        return `${this.name} is studying for ${this.grade}.`;
    }
}
let alice = new Student("Alice", "10th");
console.log(alice.study()); // "Alice is studying for 10th."

3. Prototypes (Advanced)

Objects inherit properties from a prototype. Example:

let teacher = {
    teach: function() {
        return `${this.name} is teaching.`;
    }
};
let mathTeacher = Object.create(teacher);
mathTeacher.name = "Mr. Smith";
console.log(mathTeacher.teach()); // "Mr. Smith is teaching."

Real-World Tie-In: eSewa’s User Accounts eSewa stores user data as objects/classes:

class User {
    constructor(email, balance) {
        this.email = email;
        this.balance = balance;
        this.transactions = [];
    }
    addTransaction(amount, type) {
        this.transactions.push({amount, type, timestamp: new Date()});
        this.balance += amount;
    }
}
  • Why objects? To encapsulate user data (email, balance, transactions) and methods (e.g., addTransaction).
  • Why classes? To create multiple user instances efficiently.

Form Validation with JavaScript

Forms must validate data before submission to avoid server errors. Common checks:

  1. Required fields (e.g., username, email).
  2. Format validation (e.g., email regex, password length).
  3. Custom rules (e.g., age ≥ 18, password strength).

Example: Signup Form Validation

<form id="signupForm">
    <input type="text" id="name" placeholder="Name" required>
    <input type="email" id="email" placeholder="Email" required>
    <input type="password" id="password" placeholder="Password" minlength="8">
    <button type="submit">Sign Up</button>
</form>
<p id="error"></p>

<script>
    document.getElementById("signupForm").addEventListener("submit", function(e) {
        e.preventDefault(); // Stop form submission
        let errorMsg = "";
        let name = document.getElementById("name").value;
        let email = document.getElementById("email").value;
        let password = document.getElementById("password").value;

        // Validation logic
        if (name.trim() === "") errorMsg += "Name is required.\n";
        if (!email.includes("@")) errorMsg += "Invalid email.\n";
        if (password.length < 8) errorMsg += "Password must be 8+ characters.";

        if (errorMsg) {
            document.getElementById("error").innerHTML = errorMsg;
        } else {
            alert("Form submitted successfully!");
            // this.submit(); // Uncomment to submit
        }
    });
</script>

Real-World Tie-In: Daraz’s Checkout Process Daraz validates:

  1. Shipping address: Checks if fields (street, city, pincode) are filled.
  2. Payment: Validates card details using regex (e.g., ^\d{16}$ for card numbers).
  3. Coupon codes: Ensures codes match the format DARAZ10 (letters + numbers).

Worked Example: Ncell Recharge Validation

function validateRecharge(amount) {
    let error = "";
    if (isNaN(amount)) error = "Invalid amount.";
    else if (amount < 10) error = "Minimum recharge: Rs. 10.";
    else if (amount > 5000) error = "Maximum limit: Rs. 5000.";
    return error;
}
console.log(validateRecharge(5)); // "Minimum recharge: Rs. 10."

Arrays and Loops: Working with Lists

Arrays store multiple values in a single variable. Loops iterate over them.

1. Array Methods

Method Example Description
push() fruits.push("apple"); Add to end.
pop() fruits.pop(); Remove from end.
map() fruits.map(fruit => fruit.toUpperCase()); Transform each item.
filter() numbers.filter(n => n > 10); Return items meeting a condition.

Example: Processing a Fruit Array

let fruits = ["apple", "banana", "mango"];
fruits.push("grape"); // ["apple", "banana", "mango", "grape"]
let upperFruits = fruits.map(fruit => fruit.toUpperCase());
console.log(upperFruits); // ["APPLE", "BANANA", "MANGO", "GRAPE"]

2. Loops

Loop Type Syntax Example Use Case
for for (let i = 0; i < 5; i++) { ... } Known iterations.
for...of for (let fruit of fruits) { ... } Iterate over arrays/objects.
while while (condition) { ... } Unknown iterations.

Example: Validating All Form Fields

let formFields = ["name", "email", "password"];
let isValid = true;
for (let field of formFields) {
    let value = document.getElementById(field).value;
    if (value.trim() === "") {
        isValid = false;
        break;
    }
}
console.log(isValid); // false if any field is empty

Real-World Tie-In: Kathmandu Traffic Routes Imagine a system to validate bus routes:

let routes = ["KTM-TL", "KTM-BHR", "KTM-DH"];
function validateRoute(route) {
    return routes.includes(route);
}
console.log(validateRoute("KTM-POK")); // false (invalid route)

AJAX: Asynchronous Data Fetching

AJAX (Asynchronous JavaScript And XML) lets web pages fetch data from servers without reloading. Used by:

  • eSewa (checking balance).
  • Daraz (loading product details dynamically).
  • NTC (real-time flight status).

Example: Fetching Data with XMLHttpRequest

let xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.esewa.com/balance", true);
xhr.onload = function() {
    if (xhr.status === 200) {
        let balance = JSON.parse(xhr.responseText).balance;
        document.getElementById("balance").innerHTML = `Rs. ${balance}`;
    }
};
xhr.send();
Step 1Create XMLHttpRequest objectStep 2Set request method(GET/POST) and URLStep 3Send request(asynchronous)Step 4Handle response inonreadystatechange
AJAX request lifecycle

Modern Alternative: fetch() API

fetch("https://api.esewa.com/balance")
    .then(response => response.json())
    .then(data => {
        document.getElementById("balance").innerHTML = `Rs. ${data.balance}`;
    })
    .catch(error => console.error("Error:", error));

Real-World Tie-In: WhatsApp Web WhatsApp Web uses AJAX to:

  1. Fetch messages from the server without refreshing.
  2. Update the online status of contacts in real-time.
  3. Load media (images/videos) dynamically as you scroll.

## In the Real World

  1. eSewa’s Balance Check

    • Idea Used: AJAX (fetch()) to asynchronously fetch user balance from the server.
    • How: When you click "Check Balance," the app sends a request to eSewa’s API and updates the DOM with the response without reloading the page.
    • Code Snippet:
      async function checkBalance() {
          let response = await fetch("/api/balance", { headers: { "Authorization": "Bearer YOUR_TOKEN" } });
          let data = await response.json();
          document.getElementById("balance").textContent = `Rs. ${data.amount}`;
      }
      
  2. Pathao’s Ride Tracking

    • Idea Used: DOM manipulation + setInterval() for real-time updates.
    • How: The app polls the driver’s location every 5 seconds and updates the map’s marker position using:
      setInterval(() => {
          fetch("/api/driver-location")
              .then(res => res.json())
              .then(pos => {
                  document.getElementById("driver-lat").textContent = pos.lat;
                  document.getElementById("driver-lng").textContent = pos.lng;
                  // Update map marker
              });
      }, 5000);
      
  3. Daraz’s Cart Validation

    • Idea Used: Form validation + object-oriented JavaScript.
    • How: Daraz validates:
      • Coupon codes (regex: ^[A-Z]{3}\d{2}$).
      • Payment methods (objects for each method: CreditCard, Khalti, Esewa).
      • Stock availability (AJAX call to check inventory before checkout).
    • Example Validation:
      class Cart {
          constructor() {
              this.items = [];
          }
          validateCoupon(code) {
              return /^[A-Z]{3}\d{2}$/.test(code);
          }
      }
      let cart = new Cart();
      console.log(cart.validateCoupon("DAR12")); // true
      

## Exam Tip

  1. Form Validation Questions (30% Weight)

    • Always validate:
      • Required fields (value.trim() === "").
      • Email format (/^[^\s@]+@[^\s@]+\.[^\s@]+$/).
      • Password strength (length ≥ 8, special characters).
    • Structure your answer:
      function validateForm() {
          let isValid = true;
          // Check each field
          if (!nameValid) { errorMsg += "Name error.\n"; isValid = false; }
          if (!emailValid) { errorMsg += "Email error.\n"; isValid = false; }
          return { isValid, errorMsg };
      }
      
  2. DOM Manipulation (25% Weight)

    • Use querySelector for dynamic elements (e.g., document.querySelector(".product")).
    • For events, always use addEventListener (not inline onclick).
    • Common tasks:
      • Change text: element.innerHTML = "New text";
      • Toggle visibility: element.style.display = "none";
      • Add classes: element.classList.add("active");
  3. Objects and Arrays (20% Weight)

    • For objects: Use dot notation (obj.property) or bracket notation (obj["property"]).
    • For arrays: Practice map(), filter(), and forEach().
    • Class questions: Always include:
      • constructor() for initialization.
      • Methods (e.g., calculateTotal() for a Cart class).
  4. AJAX (15% Weight)

    • Use fetch() (modern) over XMLHttpRequest.
    • Structure:
      fetch(url)
          .then(response => response.json())
          .then(data => { /* Update DOM */ })
          .catch(error => console.error(error));
      
    • Real-world twist: Relate to APIs like eSewa’s balance check or Daraz’s product search.
  5. Avoid Common Mistakes

    • ❌ Using == instead of === (type coercion issues).
    • ❌ Forgetting e.preventDefault() in form submissions.
    • ❌ Not handling errors in AJAX calls (always use .catch()).

Based on the TU BSc CSIT syllabus for Web Technology (CSC318), unit 5.

Discussion

Loading…