Unit 5 - Notes

CSE326

Unit 5: JavaScript Functions, Events and Validation

1. Working with Functions

Functions are fundamental building blocks in JavaScript. A function is a block of code designed to perform a particular task, executed when "called" (invoked).

1.1 Function Definition and Syntax

A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().

JAVASCRIPT
// Function Declaration
function functionName(parameter1, parameter2) {
    // code to be executed
}

1.2 Using Function Arguments

Arguments are the values received by the function when it is invoked. Parameters are the names listed in the function's definition.

  • Pass-by-Value: Primitive types (numbers, strings) are passed by value. Changing the variable inside the function does not affect the outer variable.
  • Pass-by-Reference: Objects and Arrays are passed by reference. Changing properties inside the function affects the original object.

Example: Using Arguments

JAVASCRIPT
function greetUser(name, timeOfDay) {
    console.log("Good " + timeOfDay + ", " + name + "!");
}

// Invoking the function with arguments
greetUser("Alice", "Morning"); // Output: Good Morning, Alice!
greetUser("Bob", "Evening");   // Output: Good Evening, Bob!

The arguments Object

JavaScript functions have a built-in object called arguments. It contains an array-like list of all arguments passed to the function, useful when the number of arguments is unknown in advance.

JAVASCRIPT
function sumAll() {
    let sum = 0;
    for (let i = 0; i < arguments.length; i++) {
        sum += arguments[i];
    }
    return sum;
}

console.log(sumAll(1, 12, 50)); // Output: 63

1.3 The Return Statement

The return statement stops the execution of a function and returns a value to the function caller. If the return statement is omitted, the function returns undefined.

Key characteristics:

  • It terminates function execution immediately.
  • It can return any data type (String, Number, Boolean, Array, Object, Function).

Example: Calculating and Returning Values

JAVASCRIPT
function calculateArea(width, height) {
    if (width < 0 || height < 0) {
        return "Invalid dimensions"; // Stops execution here if true
    }
    let area = width * height;
    return area; // Returns the calculated value
}

let result = calculateArea(5, 10);
console.log(result); // Output: 50


2. Working with JavaScript Events

Events are actions or occurrences that happen in the system you are programming, which the system tells you about so you can respond to them. JavaScript interacts with HTML via the Document Object Model (DOM) to handle these events.

2.1 Event Handling Mechanisms

  1. Inline Events (HTML Attributes): <button onclick="myFunc()"> (Not recommended for large apps).
  2. DOM Property Binding: element.onclick = myFunc;
  3. Event Listeners (Standard): element.addEventListener('event', function);

2.2 Mouse Based Events

These events occur when the user interacts with the mouse or a pointing device.

Event Description
click Triggered when the user clicks on an element.
dblclick Triggered when the user double-clicks an element.
mousedown Triggered when a mouse button is pressed down over an element.
mouseup Triggered when a mouse button is released over an element.
mousemove Triggered when the mouse pointer moves while it is over an element.
mouseover Triggered when the mouse pointer moves onto an element.
mouseout Triggered when the mouse pointer moves out of an element.

Example: Mouse Over and Click

HTML
<div id="box" style="width:100px; height:100px; background:blue;"></div>

<script>
    const box = document.getElementById('box');

    // Change color on mouse over
    box.addEventListener('mouseover', function() {
        box.style.backgroundColor = 'red';
    });

    // Revert color on mouse out
    box.addEventListener('mouseout', function() {
        box.style.backgroundColor = 'blue';
    });

    // Alert on click
    box.addEventListener('click', function() {
        alert("Box clicked!");
    });
</script>

2.3 Keyboard Based Events

These events are generated by the keyboard. They are essential for form inputs and game controls.

Event Description
keydown Triggered when the user presses a key. Repeated if the key is held down.
keyup Triggered when the user releases a key.
keypress (Deprecated) Triggered when a key produces a character value. Use keydown instead.

Example: Input Character Counter

HTML
<input type="text" id="msgInput" placeholder="Type something...">
<p>Character count: <span id="count">0</span></p>

<script>
    const input = document.getElementById('msgInput');
    const display = document.getElementById('count');

    input.addEventListener('keyup', function() {
        // Update count every time a key is released
        display.innerText = input.value.length;
    });
</script>

2.4 Form Based Events

These events are specific to HTML form elements.

Event Description
submit Triggered when a form is submitted. Crucial for validation.
focus Triggered when an element gets focus (e.g., clicked into).
blur Triggered when an element loses focus (e.g., clicked away).
change Triggered when the content of a form element changes (for inputs, triggers after losing focus).
input Triggered immediately when the value of an <input> or <textarea> element is changed.

3. JavaScript Form Validation

Form validation ensures that the data entered by the user into a web form is accurate and complete before it is sent to the server.

3.1 Basics of Validation

  • Required Validation: Checking if a field is empty.
  • Format Validation: Checking if the data matches a pattern (e.g., email, date).
  • Data Integrity: Checking if passwords match or if numbers fall within a range.

3.2 Implementation Strategy

To validate a form, we typically hook into the form's submit event. If validation fails, we call event.preventDefault() to stop the data from being sent to the server.

3.3 Comprehensive Validation Example

HTML Structure:

HTML
<form id="regForm">
    <label>Username:</label>
    <input type="text" id="username"><br><br>
    
    <label>Email:</label>
    <input type="text" id="email"><br><br>
    
    <label>Password:</label>
    <input type="password" id="password"><br><br>
    
    <button type="submit">Register</button>
    <p id="errorMsg" style="color:red;"></p>
</form>

JavaScript Validation Logic:

JAVASCRIPT
document.getElementById('regForm').addEventListener('submit', function(event) {
    // 1. Access DOM elements
    let user = document.getElementById('username').value;
    let email = document.getElementById('email').value;
    let pass = document.getElementById('password').value;
    let errorDisplay = document.getElementById('errorMsg');
    let isValid = true;
    let message = "";

    // 2. Username Validation (Required + Length)
    if (user === "") {
        message = "Username is required.";
        isValid = false;
    } else if (user.length < 5) {
        message = "Username must be at least 5 characters.";
        isValid = false;
    }

    // 3. Email Validation (Regex Pattern)
    // Simple pattern looking for character@character.domain
    let emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (isValid && !emailPattern.test(email)) {
        message = "Please enter a valid email address.";
        isValid = false;
    }

    // 4. Password Validation (Length)
    if (isValid && pass.length < 8) {
        message = "Password must be at least 8 characters long.";
        isValid = false;
    }

    // 5. Final Decision
    if (!isValid) {
        // STOP the form submission
        event.preventDefault(); 
        // Display the error to the user
        errorDisplay.innerText = message;
    } else {
        // Allow form to submit (or handle via AJAX)
        alert("Validation Successful! Submitting form...");
    }
});

3.4 Common Validation Techniques

  1. Checking for Empty Fields:

    JAVASCRIPT
        if (document.myform.Name.value == "") { 
            alert("Name cannot be empty"); 
            return false; 
        }
        

  2. Validating Numbers (isNaN):
    The isNaN() function determines whether a value is Not-a-Number.

    JAVASCRIPT
        let age = document.getElementById('age').value;
        if (isNaN(age) || age < 1 || age > 100) {
            alert("Please enter a valid age between 1 and 100");
        }
        

  3. Regular Expressions (Regex):
    Used for pattern matching (Email, Phone numbers, ZIP codes).

    JAVASCRIPT
        let phone = document.getElementById('phone').value;
        let phonePattern = /^\d{10}$/; // Matches exactly 10 digits
        if (!phonePattern.test(phone)) {
            alert("Invalid Phone Number");
        }