Mark Joshua Kylee P. Sta. Rosa & Justine Paul P. Tañada

Final Project for Web Page Programming

Introduction to Web Page Programming: A Comprehensive Overview

What is Web Development?

Web development involves creating websites and web applications, categorized into:

Front-End Development

Key Responsibilities:

Core Technologies:

Back-End Development

Key Responsibilities:

Core Technologies:

Full-Stack Development

A full-stack developer handles both front-end and back-end development, ensuring smooth integration and debugging.

Introduction to JavaScript

JavaScript enhances web pages by allowing dynamic and interactive elements.

Why Use JavaScript?

Adding JavaScript to a Web Page

  1. Inline JavaScript – Placed within <script> tags inside an HTML file.
  2. External JavaScript – Linked via a separate .js file for better code organization.

By mastering HTML, CSS, and JavaScript, developers can create functional, interactive, and user-friendly web pages.

ACTIVITY

Understanding JavaScript Data Types and Operators

Undefined vs. Null

Analyzing Data Types

Converting Data Types

Operators in JavaScript

Arithmetic Operators

Used for mathematical calculations:

Comparison Operators

Compare two values and return true or false:

Logical Operators

Combine boolean values:

Assignment Operators

Used to assign values to variables:

Understanding these fundamental concepts is crucial for efficient JavaScript programming and web development.

ACTIVITY

Understanding Logical Statements in JavaScript

Logical statements are essential in programming as they allow developers to control the flow of execution based on specific conditions. JavaScript provides several ways to implement conditional logic efficiently.


Types of Logical Statements in JavaScript

1. If, Else If, and Else Statements

2. Common Mistakes with If Statements

CONSOLE

let hobby = "coding";
if (hobby = "music") {  // Incorrect: assignment instead of comparison
    console.log("You like music!");
}
                
CONSOLE

if (hobby == "music") {  
    console.log("You like music!");
}
                

3. Else If Statements

Used when multiple conditions need to be checked. Only the first true condition executes, preventing unnecessary evaluations.

Example:

CONSOLE

let grade = 85;
if (grade >= 90) {
    console.log("Excellent!");
} else if (grade >= 75) {
    console.log("Good job!");
} else {
    console.log("Keep improving!");
}
                

4. Conditional (Ternary) Operator

CONSOLE

let age = 17;
let access = age < 18 ? "Denied" : "Allowed";
console.log(access); // Output: Denied
                

Best for short, simple conditions to improve readability.


5. Switch Statements

CONSOLE

let day = "Monday";
switch (day) {
    case "Monday":
        console.log("Start of the workweek.");
        break;
    case "Friday":
        console.log("Weekend is near!");
        break;
    case "Sunday":
        console.log("Relax and recharge.");
        break;
    default:
        console.log("It's a regular day.");
}
                

Conclusion

Understanding logical statements in JavaScript is crucial for writing efficient and dynamic programs. Whether using if-else, the ternary operator, or switch, choosing the right control structure enhances code clarity and performance. 🚀

ACTIVITY

Mastering Loops and Arrays in JavaScript

Loops are a powerful tool in JavaScript that allow programmers to execute a block of code multiple times efficiently. This chapter covers different types of loops and their applications in handling arrays and objects.


Types of Loops in JavaScript

1. While Loop

Example:

CONSOLE

let i = 0;
while (i < 5) {
    console.log(i);
    i++;
}
                

✔ Useful for scenarios where the number of iterations is unknown beforehand.

2. Do While Loop

Example:

CONSOLE

let i = 0;
do {
    console.log(i);
    i++;
} while (i < 5);
                

✔ Ensures the loop runs at least once, even if the condition is false.

3. For Loop

Example:

CONSOLE

for (let i = 0; i < 5; i++) {
    console.log(i);
}
                

✔ Efficient and commonly used in array manipulations.


Working with Arrays Using Loops

1. Finding a Value in an Array Using While Loop

Example:

CONSOLE

let numbers = [10, 20, 30, 40, 50];
let i = 0;
while (i < numbers.length) {
    if (numbers[i] === 30) {
        console.log("Value found!");
        break;
    }
    i++;
}
                

✔ Helps search elements dynamically.

2. Creating Arrays with a For Loop

Example:

CONSOLE

let evenNumbers = [];
for (let i = 2; i <= 10; i += 2) {
    evenNumbers.push(i);
}
console.log(evenNumbers); // Output: [2, 4, 6, 8, 10]
                

✔ Great for generating sequences programmatically.

3. Nested Loops

Example:

CONSOLE

for (let i = 1; i <= 3; i++) {
    for (let j = 1; j <= 3; j++) {
        console.log(`i=${i}, j=${j}`);
    }
}
                

✔ Useful for working with tables and matrices.


Looping Through Objects

1. For-In Loop (Iterating Over Object Properties)

Example:

CONSOLE

let person = { name: "Alice", age: 25, city: "New York" };
for (let key in person) {
    console.log(`${key}: ${person[key]}`);
}
                

✔ Best suited for iterating over object properties.

2. Converting Objects to Arrays for Iteration

Convert keys to an array:

CONSOLE

let keys = Object.keys(person);
console.log(keys); // Output: ["name", "age", "city"]
                

Convert values to an array:

CONSOLE

let values = Object.values(person);
console.log(values); // Output: ["Alice", 25, "New York"]
                

Convert entries to an array:

CONSOLE

let entries = Object.entries(person);
console.log(entries); // Output: [["name", "Alice"], ["age", 25], ["city", "New York"]]
                

✔ Provides flexibility in iterating through object data.


Conclusion

Loops are an essential part of JavaScript that help in handling arrays and objects efficiently. Understanding when to use different types of loops can significantly improve the readability and performance of your code. Mastering loops allows developers to automate repetitive tasks and handle complex data structures with ease. 🚀

ACTIVITY

Understanding JavaScript Functions

Functions are one of the fundamental building blocks of JavaScript, allowing developers to write reusable, modular, and efficient code. This chapter explores function syntax, calling functions, returning values, using arguments, and integrating functions into HTML for dynamic web pages.


Key Concepts of JavaScript Functions

1. What Are Functions?

Basic Syntax:

CONSOLE

function greet() {
    console.log("Hello, world!");
}
greet(); // Calls the function
                

✔ Helps organize and structure code for better readability.


2. Integrating Functions in HTML

Example:

CONSOLE

<button onclick="sayHello()">Click Me</button>

<script>
function sayHello() {
    alert("Hello, User!");
}
</script>
                

✔ Enhances interactivity in web applications.


3. Functions Calling Other Functions

Example:

CONSOLE

function firstFunction() {
    console.log("Calling second function...");
    secondFunction();
}

function secondFunction() {
    console.log("Hello from second function!");
}

firstFunction();
                

✔ Helps break down complex logic into smaller, manageable parts.


4. Returning Values from Functions

Example:

CONSOLE

function add(a, b) {
    return a + b;
}

let sum = add(5, 3);
console.log(sum); // Output: 8
                

✔ Useful for calculations, data manipulation, and dynamic operations.


5. Function Arguments

Example:

CONSOLE

function greetUser(name, age) {
    console.log(`Hello, ${name}! You are ${age} years old.`);
}

greetUser("Alice", 25);
                

✔ Increases function flexibility and reusability.


Conclusion

JavaScript functions are essential for writing efficient and modular code. They allow developers to break down tasks, reuse logic, and enhance web page interactivity. Mastering functions is key to writing scalable and maintainable JavaScript applications. 🚀

ACTIVITY

Exploring Built-in JavaScript Methods

JavaScript provides a wide range of built-in methods that simplify common programming tasks. These predefined functions help developers manipulate strings, arrays, numbers, and even execute dynamic JavaScript code efficiently. This chapter explores global methods, URI encoding/decoding, number parsing, and security concerns with eval().


Key JavaScript Built-in Methods

1. What Are Built-in Methods?

✔ Example of Method Chaining:

CONSOLE

let text = "Hello World";
console.log(text.toLowerCase().replace("hello", "Hi"));
                

2. Global JavaScript Methods

✔ Example:

CONSOLE

console.log(parseInt("42px")); // Output: 42
console.log(parseFloat("3.14")); // Output: 3.14
                

3. Encoding & Decoding URIs

✔ Example:

CONSOLE

let url = "https://example.com?name=John Doe";
let encodedURL = encodeURI(url);
console.log(encodedURL); // Encodes spaces and special characters
                

4. Executing JavaScript with eval()

✔ Example (Avoid using eval() in production):

CONSOLE

let x = 10;
let code = "x * 2";
console.log(eval(code)); // Output: 20
                

🚨 Never use eval() for user-generated inputs!


5. Array Methods

✔ Example of map():

CONSOLE

let numbers = [1, 2, 3, 4];
let doubled = numbers.map(num => num * 2);
console.log(doubled); // Output: [2, 4, 6, 8]
                

6. String Methods

✔ Example:

CONSOLE

let sentence = "Hello, JavaScript!";
console.log(sentence.split(" ")); // Output: ["Hello,", "JavaScript!"]
                

Conclusion

Built-in JavaScript methods simplify coding by providing pre-defined solutions for common tasks. Mastering these methods can enhance productivity and make code more efficient. 🚀

ACTIVITY

Understanding the Document Object Model (DOM)

The Document Object Model (DOM) is essential for JavaScript developers working with web pages. It transforms an HTML document into a tree structure, allowing dynamic interactions. This chapter explores HTML fundamentals, the Browser Object Model (BOM), and DOM manipulation techniques.


1. HTML Basics

HTML (HyperText Markup Language) is the backbone of web pages. Browsers interpret HTML to render content.

Major HTML Elements:

Common HTML Tags:


2. Browser Object Model (BOM)

The BOM provides access to browser-specific properties and functions.

Key BOM Objects:

Inspecting BOM Using Developer Tools:

  1. Press F12 or right-click → "Inspect".
  2. Navigate to the Console tab.
  3. Use console.dir(window) to explore available properties.

Example – Accessing Browser History Length:

CONSOLE

console.log(history.length); // Number of visited pages
                

3. Understanding the DOM Structure

The DOM represents an HTML document as a logical tree, allowing JavaScript to modify elements dynamically.

DOM Tree Example:

CONSOLE

<html>
 ├── <head>
 └── <body>
      ├── <div>
      ├── <p>
      └── <button>
            

4. Selecting Page Elements

To manipulate web elements, they must be selected first.

Selection Methods:

Example – Selecting Elements:

CONSOLE

let title = document.querySelector("h1");
console.log(title.textContent); // Logs the text inside
                

Example – Selecting Multiple Elements:

CONSOLE

let items = document.querySelectorAll("li");
items.forEach(item => console.log(item.textContent));
                

Conclusion

Mastering the DOM and BOM is crucial for building interactive web applications. By learning how to inspect, select, and manipulate web elements, developers can create dynamic, user-friendly experiences. 🚀

ACTIVITY

Interactive Web Content and Event Listeners

Creating interactive web content enhances user engagement by responding to actions like clicks, typing, or hovering. This chapter explores event handling techniques, from basic event specification to advanced event listeners.


1. Understanding Interactive Content

Interactive content modifies the DOM based on user input. Common examples include:


2. Event Handling in JavaScript

Events define how elements react to user interactions. There are three ways to specify events:

  1. HTML-based events – Directly within the tag (e.g., onclick="functionName()").
  2. JavaScript-based events – Assign functions to element properties.
  3. Event Listeners – Use addEventListener() for multiple event functions.

Example – Adding an Event Listener:

CONSOLE

document.getElementById("myButton").addEventListener("click", function() {
    alert("Button clicked!");
});
                

3. Common Event Handlers

Mouse Events:

Example – Changing Background Color on Mouse Events:

CONSOLE

myDiv.addEventListener("mousedown", () => myDiv.style.background = "green");
myDiv.addEventListener("mouseup", () => myDiv.style.background = "yellow");
myDiv.addEventListener("dblclick", () => myDiv.style.background = "black");
myDiv.addEventListener("mouseout", () => myDiv.style.background = "blue");
                

Keyboard Events:

Example – Detecting Key Presses:

CONSOLE

document.addEventListener("keydown", (event) => {
    console.log("Key pressed: " + event.key);
});
                

4. DOM Event Flow

Events propagate through elements in two ways:

Example – Event Bubbling:

CONSOLE

document.getElementById("child").addEventListener("click", () => alert("Child clicked"));
document.getElementById("parent").addEventListener("click", () => alert("Parent clicked"));
                

(Clicking on "child" triggers both alerts due to bubbling.)


5. Form Events: onchange and onblur

Example – Detecting Input Changes:

CONSOLE

document.getElementById("nameInput").addEventListener("change", () => alert("Input changed!"));
                

Conclusion

Event listeners and handlers enable dynamic user interactions in web pages. By mastering mouse events, keyboard inputs, and event propagation, developers can build highly interactive and responsive applications. 🚀

ACTIVITY

Intermediate JavaScript: Advanced Concepts and Techniques

This chapter explores key intermediate JavaScript concepts that enhance functionality, optimize performance, and improve code quality. Topics include regular expressions, functions, hoisting, strict mode, debugging, cookies, local storage, and JSON.


1. Regular Expressions (Regex)

Regex helps in pattern matching, form validation, and text manipulation.

Key Features:

Quantifiers:

Example – Email Validation:

CONSOLE

let emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}$/;
console.log(emailPattern.test("example@email.com"));
                

2. Functions and Arguments Object

JavaScript functions handle arguments dynamically, allowing flexible parameter usage.

Using Arguments Object:

CONSOLE

function sum() {
    let total = 0;
    for (let num of arguments) {
        total += num;
    }
    return total;
}
console.log(sum(5, 10, 15)); // 30
                

Modern Approach – Rest Parameter:

CONSOLE

function sum(...numbers) {
    return numbers.reduce((a, b) => a + b, 0);
}
console.log(sum(5, 10, 15)); // 30
                

3. JavaScript Hoisting

Hoisting moves variable and function declarations to the top of their scope.

Example – Hoisting Behavior:

CONSOLE

console.log(x); // undefined (due to hoisting)
var x = 10;
                

Avoiding Hoisting Issues – Use let or const:

CONSOLE

console.log(y); // Error (let does not hoist)
let y = 10;
                

4. Strict Mode ("use strict")

Strict mode enforces better coding practices and prevents silent errors.

Enabling Strict Mode:

CONSOLE

"use strict";
x = 10; // Error: x is not defined
                

5. Debugging in JavaScript

Debugging helps identify and fix errors using browser tools.

Key Debugging Techniques:

Example – Using try...catch:

CONSOLE

try {
    let result = riskyOperation();
} catch (error) {
    console.error("An error occurred:", error.message);
}
                

Conclusion

Mastering regex, functions, hoisting, strict mode, and debugging enables better JavaScript programming. These techniques enhance performance, improve code maintainability, and ensure error-free execution. 🚀

ACTIVITY

Enhancing Web Applications with HTML5, Canvas, and JavaScript

The advent of HTML5 has significantly broadened the horizons for web developers, introducing elements like <canvas> that, when combined with JavaScript, enable the creation of rich graphics, dynamic content, and interactive applications. This chapter delves into key features such as the FileReader API, Geolocation API, and the Canvas API, illustrating how they can be harnessed to build engaging web experiences.


1. HTML5 and JavaScript Integration

HTML5, standardized in 2014, introduced semantic elements like <header>, <nav>, and <article>, enhancing the structure and accessibility of web pages. Notably, the <canvas> element provides a drawable region that, through JavaScript, facilitates the rendering of graphics and animations directly in the browser.


2. Reading Local Files with the FileReader API

The FileReader API empowers web applications to asynchronously read the contents of files selected by users, enabling functionalities like file previews and client-side processing.

Example – Reading a Text File:

CONSOLE

<input type="file" id="fileInput" />
<pre id="fileContent"></pre>

<script>
  document.getElementById('fileInput').addEventListener('change', function(event) {
    const file = event.target.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = function(e) {
        document.getElementById('fileContent').textContent = e.target.result;
      };
      reader.readAsText(file);
    }
  });
</script>
                

In this example, when a user selects a text file, its content is read and displayed within a <pre> element.


3. Accessing Geolocation Data

The Geolocation API allows web applications to access the geographical location of a user's device, facilitating location-based services.

Example – Retrieving Current Position:

CONSOLE

<button onclick="getLocation()">Get Location</button>
<p id="location"></p>

<script>
  function getLocation() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(showPosition);
    } else {
      document.getElementById('location').textContent = 'Geolocation is not supported by this browser.';
    }
  }

  function showPosition(position) {
    const lat = position.coords.latitude;
    const lon = position.coords.longitude;
    document.getElementById('location').textContent = `Latitude: ${lat}, Longitude: ${lon}`;
  }
</script>
                

Upon clicking the button, the application retrieves and displays the user's current latitude and longitude.


4. Drawing with the Canvas API

The <canvas> element, introduced in HTML5, provides a versatile space for rendering graphics via JavaScript. By accessing the 2D rendering context, developers can draw shapes, text, images, and more.

Example – Drawing a Rectangle:

CONSOLE

<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;"></canvas>

<script>
  const canvas = document.getElementById('myCanvas');
  const ctx = canvas.getContext('2d');
  ctx.fillStyle = '#FF0000';
  ctx.fillRect(50, 25, 100, 50);
</script>
                

This script draws a red rectangle on the canvas.


Conclusion

The integration of HTML5 elements with JavaScript APIs like FileReader, Geolocation, and Canvas has revolutionized web development, enabling the creation of dynamic, interactive, and user-centric applications. Mastering these tools empowers developers to craft engaging web experiences that leverage the full capabilities of modern browsers.

ACTIVITY