Exercises Overview

Welcome to the Part 3 exercises! These hands-on activities will help you master JavaScript for web development. Complete each exercise to build your skills in creating interactive web pages.

Your Progress

Complete exercises to track your progress

JavaScript Basics Exercises

3.1

Hello JavaScript

Your first interactive web page

Beginner

Create an HTML page with JavaScript that displays "Hello, World!" and includes interactive elements like buttons that change content. This exercise will help you understand how to add JavaScript to web pages.

Detailed Instructions

  1. Create an HTML file: Save as "hello-javascript.html"
  2. Add basic HTML structure: Include DOCTYPE, html, head, and body tags
  3. Create a button: Add a button element with an ID
  4. Add a display element: Create a paragraph or div to show messages
  5. Write JavaScript: Use <script> tag or external JS file
  6. Select elements: Use getElementById or querySelector
  7. Add event listener: Listen for button clicks
  8. Change content: Update the display element when button is clicked

Complete HTML with JavaScript Template

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello JavaScript</title>
</head>
<body>
    <h1>Hello JavaScript!</h1>
    <p id="message">Click the button to see a message!</p>
    <button id="clickBtn">Click Me</button>

    <script>
        // Select elements
        const button = document.getElementById('clickBtn');
        const message = document.getElementById('message');

        // Add event listener
        button.addEventListener('click', function() {
            message.textContent = 'Hello, World! JavaScript is working!';
        });
    </script>
</body>
</html>

What to Include

  • HTML structure: Basic HTML5 document with button and display element
  • JavaScript selection: Use getElementById or querySelector to select elements
  • Event listener: Add click event listener to the button
  • Content change: Update text content when button is clicked
  • Test functionality: Verify the button changes the message when clicked

Challenge Yourself

  • Add multiple buttons that display different messages
  • Change the button text after it's been clicked
  • Add a counter that shows how many times the button was clicked
  • Style the message with different colors based on button clicks

Submit Your Work

Please compress your HTML file and any related files into a ZIP archive. Name your file as: lastname_first_name_course_year_section_exercise_3.1. Maximum file size: 5MB.
3.2

Interactive Calculator

Build a simple calculator

Intermediate

Create a simple calculator that can add, subtract, multiply, and divide two numbers. Include input fields for numbers and buttons for operations. Display the result dynamically.

Detailed Instructions

  1. Create HTML structure: Add input fields for two numbers and operation buttons
  2. Add display element: Create a div or paragraph to show the result
  3. Create JavaScript functions: Write functions for each operation (add, subtract, multiply, divide)
  4. Get input values: Read values from input fields using .value property
  5. Perform calculations: Execute the appropriate operation based on button clicked
  6. Display results: Show the result in the display element
  7. Add error handling: Handle cases where inputs are empty or invalid

Calculator JavaScript Template

function addNumbers() {
    const num1 = parseFloat(document.getElementById('num1').value);
    const num2 = parseFloat(document.getElementById('num2').value);
    const result = num1 + num2;
    document.getElementById('result').textContent = 'Result: ' + result;
}

// Add similar functions for subtract, multiply, and divide

Required Features

  • Input fields: Two number inputs with proper labels
  • Operation buttons: Buttons for add, subtract, multiply, divide
  • Result display: Element to show calculation results
  • JavaScript functions: Functions for each mathematical operation
  • Error handling: Check for valid numbers before calculating

Challenge Yourself

  • Add a "Clear" button to reset all inputs
  • Support decimal numbers
  • Add validation to prevent division by zero
  • Style the calculator with CSS

Submit Your Work

Please compress your HTML file and any related files into a ZIP archive. Name your file as: lastname_first_name_course_year_section_exercise_3.2. Maximum file size: 5MB.

DOM Manipulation Exercises

3.3

Dynamic List Manager

Add and remove list items dynamically

Intermediate

Create a to-do list application where users can add new items and remove existing ones. Practice DOM manipulation by creating, modifying, and deleting HTML elements with JavaScript.

Detailed Instructions

  1. Create HTML structure: Add an input field, "Add" button, and empty list (ul)
  2. Write add function: Get input value, create new li element, append to list
  3. Add delete functionality: Include delete button in each list item
  4. Handle empty inputs: Prevent adding empty items
  5. Clear input after adding: Reset input field after adding item
  6. Test all features: Verify adding and deleting items works correctly

List Manager JavaScript Template

function addItem() {
    const input = document.getElementById('itemInput');
    const itemText = input.value.trim();

    if (itemText === '') {
        return; // Don't add empty items
    }

    const list = document.getElementById('todoList');
    const newItem = document.createElement('li');
    newItem.textContent = itemText;

    const deleteBtn = document.createElement('button');
    deleteBtn.textContent = 'Delete';
    deleteBtn.addEventListener('click', () => {
        newItem.remove();
    });

    newItem.appendChild(deleteBtn);
    list.appendChild(newItem);
    input.value = ''; // Clear input
}

Required Features

  • Add items: Input field and button to add new list items
  • Display items: Dynamically created list items
  • Delete items: Each item should have a delete button
  • Input validation: Prevent adding empty items
  • DOM manipulation: Create and remove elements dynamically

Challenge Yourself

  • Add checkbox to mark items as complete
  • Add edit functionality to modify existing items
  • Save items to localStorage so they persist
  • Add item count display

Submit Your Work

Please compress your HTML file and any related files into a ZIP archive. Name your file as: lastname_first_name_course_year_section_exercise_3.3. Maximum file size: 5MB.
3.4

Color Changer

Change page colors dynamically

Beginner

Create a page with buttons that change the background color, text color, and other styles dynamically. Practice using JavaScript to modify CSS properties of elements.

Color Changer JavaScript Template

function changeBackgroundColor(color) {
    document.body.style.backgroundColor = color;
}

// Add event listeners to color buttons
document.getElementById('redBtn').addEventListener('click', () => {
    changeBackgroundColor('red');
});

Required Features

  • Color buttons: Buttons for different colors (red, blue, green, etc.)
  • Background changer: Change body background color
  • Text color changer: Change text color of headings or paragraphs
  • Reset button: Button to restore original colors

Submit Your Work

Please compress your HTML file and any related files into a ZIP archive. Name your file as: lastname_first_name_course_year_section_exercise_3.4. Maximum file size: 5MB.

Event Handling Exercises

3.5

Interactive Image Gallery

Create a clickable image gallery

Intermediate

Build an image gallery with thumbnail images. When a thumbnail is clicked, display the full-size image. Include previous/next navigation buttons. Practice event handling and DOM manipulation.

Features to Implement

  • Thumbnail grid: Display multiple thumbnail images
  • Main image display: Show selected image in larger view
  • Click events: Click thumbnails to change main image
  • Navigation buttons: Previous/Next buttons to cycle through images
  • Keyboard support: Use arrow keys to navigate (optional)

Submit Your Work

Please compress your HTML file and any related files into a ZIP archive. Name your file as: lastname_first_name_course_year_section_exercise_3.5. Maximum file size: 5MB.
3.6

Mouse Events Demo

Practice various mouse events

Beginner

Create a page that responds to different mouse events: click, double-click, mouseover, mouseout, and mousemove. Display messages or change styles based on these events.

Mouse Events Template

const element = document.getElementById('myElement');

element.addEventListener('click', () => {
    console.log('Clicked!');
});

element.addEventListener('mouseover', () => {
    element.style.backgroundColor = 'yellow';
});

element.addEventListener('mouseout', () => {
    element.style.backgroundColor = 'white';
});

Submit Your Work

Please compress your HTML file and any related files into a ZIP archive. Name your file as: lastname_first_name_course_year_section_exercise_3.6. Maximum file size: 5MB.

Form Validation Exercises

3.7

Contact Form with Validation

Build a validated contact form

Intermediate

Create a contact form with name, email, phone, and message fields. Add JavaScript validation to check all fields before submission. Display error messages for invalid inputs.

Validation Rules

  • Name: Required, at least 2 characters
  • Email: Required, must contain @ symbol and valid format
  • Phone: Optional, but if provided must be valid format
  • Message: Required, at least 10 characters

Form Validation Template

form.addEventListener('submit', function(e) {
    e.preventDefault(); // Prevent form submission

    const name = document.getElementById('name').value.trim();
    const email = document.getElementById('email').value.trim();

    let isValid = true;

    // Validate name
    if (name.length < 2) {
        showError('name', 'Name must be at least 2 characters');
        isValid = false;
    }

    // Validate email
    const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailPattern.test(email)) {
        showError('email', 'Please enter a valid email address');
        isValid = false;
    }

    if (isValid) {
        alert('Form submitted successfully!');
        form.reset();
    }
});

Submit Your Work

Please compress your HTML file and any related files into a ZIP archive. Name your file as: lastname_first_name_course_year_section_exercise_3.7. Maximum file size: 5MB.
3.8

Real-Time Form Validation

Validate as user types

Advanced

Enhance the contact form with real-time validation. Show error messages and change input border colors as users type. Use the 'input' event for immediate feedback.

Real-Time Validation Template

const emailInput = document.getElementById('email');

emailInput.addEventListener('input', function() {
    const email = this.value;
    const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

    if (email && !emailPattern.test(email)) {
        showError('email', 'Invalid email format');
        this.style.borderColor = 'red';
    } else {
        clearError('email');
        this.style.borderColor = 'green';
    }
});

Submit Your Work

Please compress your HTML file and any related files into a ZIP archive. Name your file as: lastname_first_name_course_year_section_exercise_3.8. Maximum file size: 5MB.

Bonus Challenges

Take Your Skills Further

Ready for more? Try these challenges to push your JavaScript skills to the next level.

Challenge 1: Interactive Quiz Application

Create a multiple-choice quiz with questions, answer options, score tracking, and a results page. Include timer functionality for an added challenge.

Challenge 2: Local Storage To-Do App

Build a complete to-do list application that saves tasks to localStorage. Include features like editing, filtering, and marking tasks as complete.

Challenge 3: Dynamic Form Builder

Create an application where users can dynamically add and remove form fields. Allow customization of field types (text, email, number, etc.).

Challenge 4: Interactive Shopping Cart

Build a shopping cart interface where users can add/remove items, update quantities, calculate totals, and display a summary.

Ready for the Next Level?

Great job completing the JavaScript exercises! You're now ready to learn back-end development with PHP.