Web Technology IUnit 48 min read

Client-Side Scripting: JavaScript, DOM, Events & Validation

Unit 4 of Web Technology I covers client-side scripting fundamentals—JavaScript syntax, DOM manipulation, event handling, form validation, and security—with real-world applications in e-commerce, banking, and dynamic web apps like eSewa and Daraz.

Core Concepts

What is Client-Side Scripting?

Client-side scripting executes on the user’s browser (not the server) to create dynamic, interactive web pages. Unlike server-side scripts (e.g., PHP), it runs instantly without page reloads. Key languages: JavaScript (JS).

stateDiagram-v2
    [*] --> User: Opens Web Page
    User --> Browser: Loads HTML/CSS
    Browser --> JS: Executes Scripts
    JS --> DOM: Manipulates Elements
    DOM --> User: Updates UI Dynamically
    User --> JS: Triggers Events
    [*]

Why use it?

  • Faster responses (no server round-trip).
  • Reduced server load.
  • Enhanced user experience (e.g., live search, animations).

JavaScript Basics

Syntax & Structure

JS is case-sensitive and uses:

  • Variables: let, const, var (avoid var in modern code).
  • Data types: string, number, boolean, object, array, null, undefined.
  • Operators: +, -, *, /, %, ==, ===, &&, ||.
// Example: Dynamic greeting
let name = prompt("Enter your name:");
alert(`Hello, ${name}! Welcome to ${new Date().getFullYear()}.`);

Real-world tie-in:

  • eSewa uses JS to validate user inputs (e.g., mobile number format) before submitting payment requests.
  • Khalti dynamically updates transaction statuses without refreshing the page.

Document Object Model (DOM)

What is the DOM?

The DOM is a tree-like representation of an HTML document. JS can:

  • Access/modify elements (e.g., change text, styles).
  • Add/remove elements dynamically.
  • Traverse the DOM hierarchy (parent → child → sibling).
HeadParagraphButtonDiv#containerBodyHTML ElementDocument
DOM tree structure showing parent-child relationships between HTML elements.

Key methods:

Method Description Example
getElementById() Selects an element by ID. document.getElementById("btn")
querySelector() Selects using CSS selectors. document.querySelector(".class")
innerHTML Gets/sets HTML content. element.innerHTML = "<b>Hi</b>"
addEventListener() Attaches event handlers. btn.addEventListener("click", func)

Worked Example: Dynamic Counter

<button id="counter">Click Me</button>
<p id="count">0</p>
let count = 0;
document.getElementById("counter").addEventListener("click", () => {
    count++;
    document.getElementById("count").textContent = count;
});

Real-world use:

  • Pathao uses DOM manipulation to update ride statuses (e.g., "Driver arrived") in real-time.

Events & Event Handling

Button ClickEvent ListenerDOM ElementCallback Function
Event flow when a button is clicked in JavaScript.

Common Events

Events trigger actions (e.g., clicks, keypresses). Key events:

  • Mouse: click, dblclick, mouseover, mouseout.
  • Keyboard: keydown, keyup, keypress.
  • Form: submit, change, focus, blur.
  • Window: load, resize, scroll.

Example: Form Validation

<input type="email" id="email" placeholder="Enter email">
<button onclick="validateEmail()">Submit</button>
function validateEmail() {
    const email = document.getElementById("email").value;
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
        alert("Invalid email format!");
    } else {
        alert("Email is valid!");
    }
}

Real-world tie-in:

  • Daraz validates product search queries in real-time (e.g., shows suggestions as you type).

Form Validation

Why Validate?

Prevents invalid data submission (e.g., empty fields, wrong formats). Types:

  1. Client-side: JS checks before submission (faster but bypassable).
  2. Server-side: Required for security (e.g., PHP/Python checks).

Common Validations:

Validation Type Example JS Code
Email user@example.com /^[^\s@]+@[^\s@]+\.[^\s@]+$/
Password (length) Min 8 chars password.length >= 8
Number (range) Age 18–65 age >= 18 && age <= 65
Required field Non-empty field.value.trim() !== ""

Worked Example: Ncell Top-up Form

<form id="topup">
    <input type="tel" id="phone" placeholder="98XXXXXXXX" required>
    <input type="number" id="amount" min="10" max="5000" required>
    <button type="submit">Proceed</button>
</form>
document.getElementById("topup").addEventListener("submit", (e) => {
    e.preventDefault(); // Stop form submission
    const phone = document.getElementById("phone").value;
    const amount = document.getElementById("amount").value;
    if (!/^98\d{8}$/.test(phone) || amount < 10) {
        alert("Invalid phone or amount!");
    } else {
        alert(`Top-up of Rs.${amount} to ${phone} initiated.`);
        // Proceed to server-side processing
    }
});

Security Considerations

Risks & Mitigations

Risk Example Mitigation
XSS (Cross-Site Scripting) Injecting <script>alert('hack')</script> Sanitize inputs: textContent vs innerHTML.
CSRF (Cross-Site Request Forgery) Forced actions (e.g., payments) Use tokens (e.g., csrf_token in forms).
Data Leakage Logging sensitive data Avoid console.log() for passwords.

Best Practices:

  • Use textContent instead of innerHTML to prevent XSS.
  • Validate both client- and server-side.
  • Never store passwords in plaintext (use hashing like bcrypt).

In the Real World

  1. eSewa (Nepal)

    • Idea: Real-time form validation for bill payments.
    • How: JS checks if the mobile number matches the format 98XXXXXXXX and if the amount is within limits before submitting to the server. This reduces failed transactions and improves user experience.
  2. Khalti (Nepal)

    • Idea: Dynamic UI updates during transactions.
    • How: JS listens for payment status events (e.g., "Processing," "Completed") and updates the UI without refreshing the page. This mimics a desktop app feel.
  3. Google Maps (Global)

    • Idea: Event-driven interactions.
    • How: JS handles events like click on map markers to show details (e.g., restaurant info) or drag to re-center the map. This creates an interactive experience without page reloads.
  4. NEPSE (Nepal Stock Exchange)

    • Idea: Live stock price updates.
    • How: JS fetches stock data via APIs (e.g., fetch()) and dynamically updates the DOM to reflect real-time prices, similar to a ticker tape.

Exam Tip

What to Expect

  1. Short Questions (2–5 marks):

    • Define: DOM, event listener, client-side scripting.
    • Write a JS snippet to:
      • Change text color.
      • Validate an email.
      • Handle a button click.
  2. Long Questions (10–15 marks):

    • Trace: Debug a given JS code snippet (e.g., why an alert isn’t showing).
    • Design: Create a form with validation for a scenario (e.g., "Design a login form for a bank").
    • Compare: Client-side vs. server-side scripting (table format).
  3. Practical (15–20 marks):

    • Build a simple interactive page (e.g., a counter, quiz app) using HTML, CSS, and JS.
    • Tip: Use console.log() to debug during exams.

Common Pitfalls:

  • Forgetting e.preventDefault() in form submissions.
  • Using == instead of === (type coercion issues).
  • Not sanitizing user inputs (risk of XSS).

Client-Side (JavaScript)Script ExecutionBrowserDOM ManipulationDOMEvent HandlingUser InterfaceDynamic Updates
Flow of client-side processing vs. server-side (PHP) for a login form.

Based on the TU BIT syllabus for Web Technology I (BIT251), unit 4.

Discussion

Loading…