← Back to Home

Module 6: HTML, CSS, and JavaScript

Learning Objectives

Introduction to Web Development

Modern web applications typically consist of three core technologies working together:

In this module, we'll explore each of these technologies and how they work together to create functional and appealing web applications that connect to backend services.

HTML Fundamentals

HTML Document Structure

Every HTML document follows a standard structure:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document Title</title>
    <link rel="stylesheet" href="styles.css">
    <script src="script.js" defer></script>
</head>
<body>
    <!-- Content goes here -->
</body>
</html>

The key parts of an HTML document are:

Common HTML Elements

HTML provides a variety of elements for structuring content:

Text Elements

Structural Elements

Interactive Elements

Media Elements

HTML Best Practices

CSS Fundamentals

CSS Syntax

CSS consists of selectors and declaration blocks:

selector {
    property: value;
    property: value;
}

CSS Selectors

CSS selectors target HTML elements to apply styles:

Common CSS Properties

Layout Properties

Visual Properties

Typography Properties

CSS Flexbox and Grid

Modern CSS layout techniques include:

CSS Best Practices

JavaScript Fundamentals

Integrating JavaScript

JavaScript can be added to HTML in three ways:

JavaScript Syntax Basics

// Variables
let name = "John";
const age = 30;

// Functions
function greet(name) {
    return `Hello, ${name}!`;
}

// Arrays
const fruits = ["apple", "banana", "orange"];

// Objects
const person = {
    name: "John",
    age: 30,
    greet() {
        console.log(`Hello, my name is ${this.name}`);
    }
};

DOM Manipulation

JavaScript can interact with the Document Object Model (DOM) to manipulate HTML elements:

// Selecting elements
const heading = document.querySelector('h1');
const paragraphs = document.querySelectorAll('p');
const button = document.getElementById('submit-button');

// Modifying content
heading.textContent = 'New Heading';
heading.innerHTML = 'New <em>Heading</em>';

// Modifying styles
heading.style.color = 'blue';
heading.classList.add('highlight');

// Creating elements
const newParagraph = document.createElement('p');
newParagraph.textContent = 'This is a new paragraph.';
document.body.appendChild(newParagraph);

// Event handling
button.addEventListener('click', function(event) {
    console.log('Button clicked!');
    event.preventDefault();
});

JavaScript and APIs

JavaScript can communicate with backend APIs using the Fetch API or XMLHttpRequest:

// Fetch API example
fetch('https://api.example.com/data')
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(data => {
        console.log('Success:', data);
        // Do something with the data
    })
    .catch(error => {
        console.error('Error:', error);
    });

// POST request example
fetch('https://api.example.com/items', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        name: 'New Item',
        description: 'This is a new item'
    })
})
    .then(response => response.json())
    .then(data => console.log('Item created:', data))
    .catch(error => console.error('Error:', error));

JavaScript Best Practices

Connecting Frontend to Backend

Creating a Simple Web Application

Let's see how HTML, CSS, and JavaScript work together to create a simple application that interacts with a DynamoDB-backed API:

HTML Structure

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Item Manager</title>
    <link rel="stylesheet" href="styles.css">
    <script src="script.js" defer></script>
</head>
<body>
    <header>
        <h1>Item Manager</h1>
    </header>
    
    <main>
        <section class="item-form">
            <h2>Add New Item</h2>
            <form id="add-item-form">
                <div class="form-group">
                    <label for="item-name">Name:</label>
                    <input type="text" id="item-name" required>
                </div>
                <div class="form-group">
                    <label for="item-description">Description:</label>
                    <textarea id="item-description" required></textarea>
                </div>
                <button type="submit">Add Item</button>
            </form>
        </section>
        
        <section class="item-list">
            <h2>Items</h2>
            <ul id="items-container">
                <!-- Items will be added here dynamically -->
            </ul>
        </section>
    </main>
    
    <footer>
        <p>© 2023 Item Manager</p>
    </footer>
</body>
</html>

CSS Styling

/* Basic reset */
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: Arial, sans-serif;
    line-height: 1.6;
    color: #333;
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
}

header {
    background-color: #f4f4f4;
    padding: 20px;
    margin-bottom: 20px;
    border-radius: 5px;
}

h1, h2 {
    margin-bottom: 15px;
    color: #444;
}

.item-form, .item-list {
    background-color: #fff;
    padding: 20px;
    margin-bottom: 20px;
    border-radius: 5px;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.form-group {
    margin-bottom: 15px;
}

label {
    display: block;
    margin-bottom: 5px;
    font-weight: bold;
}

input, textarea {
    width: 100%;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
}

button {
    background-color: #4CAF50;
    color: white;
    padding: 10px 15px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 16px;
}

button:hover {
    background-color: #45a049;
}

ul {
    list-style: none;
}

.item {
    background-color: #f9f9f9;
    padding: 15px;
    margin-bottom: 10px;
    border-radius: 4px;
    border-left: 4px solid #4CAF50;
}

.item h3 {
    margin-bottom: 5px;
}

footer {
    text-align: center;
    margin-top: 30px;
    padding: 20px;
    color: #777;
}

JavaScript for API Integration

// API endpoint
const API_URL = 'https://api.example.com/items';

// DOM elements
const form = document.getElementById('add-item-form');
const itemsContainer = document.getElementById('items-container');

// Fetch all items
async function fetchItems() {
    try {
        const response = await fetch(API_URL);
        if (!response.ok) {
            throw new Error('Failed to fetch items');
        }
        const items = await response.json();
        displayItems(items);
    } catch (error) {
        console.error('Error:', error);
        alert('Failed to load items. Please try again later.');
    }
}

// Display items in the UI
function displayItems(items) {
    itemsContainer.innerHTML = '';
    
    if (items.length === 0) {
        itemsContainer.innerHTML = '<li>No items found</li>';
        return;
    }
    
    items.forEach(item => {
        const itemElement = document.createElement('li');
        itemElement.className = 'item';
        itemElement.innerHTML = `
            <h3>${item.name}</h3>
            <p>${item.description}</p>
            <button class="delete-btn" data-id="${item.id}">Delete</button>
        `;
        itemsContainer.appendChild(itemElement);
    });
    
    // Add event listeners to delete buttons
    document.querySelectorAll('.delete-btn').forEach(button => {
        button.addEventListener('click', deleteItem);
    });
}

// Add a new item
async function addItem(event) {
    event.preventDefault();
    
    const nameInput = document.getElementById('item-name');
    const descriptionInput = document.getElementById('item-description');
    
    const newItem = {
        name: nameInput.value,
        description: descriptionInput.value
    };
    
    try {
        const response = await fetch(API_URL, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(newItem)
        });
        
        if (!response.ok) {
            throw new Error('Failed to add item');
        }
        
        // Reset form
        nameInput.value = '';
        descriptionInput.value = '';
        
        // Refresh items list
        fetchItems();
    } catch (error) {
        console.error('Error:', error);
        alert('Failed to add item. Please try again.');
    }
}

// Delete an item
async function deleteItem(event) {
    const itemId = event.target.getAttribute('data-id');
    
    try {
        const response = await fetch(`${API_URL}/${itemId}`, {
            method: 'DELETE'
        });
        
        if (!response.ok) {
            throw new Error('Failed to delete item');
        }
        
        // Refresh items list
        fetchItems();
    } catch (error) {
        console.error('Error:', error);
        alert('Failed to delete item. Please try again.');
    }
}

// Event listeners
form.addEventListener('submit', addItem);

// Load items when page loads
document.addEventListener('DOMContentLoaded', fetchItems);

Key Concepts in Frontend-Backend Integration

Key Topics

HTML Fundamentals

Learn the basics of HTML to structure your web pages.

  • HTML document structure
  • Common HTML elements
  • Forms and inputs

CSS for Styling

Learn how to style your web pages with CSS.

  • CSS selectors
  • Box model (margin, padding, border)
  • Layout techniques

JavaScript for Interactivity

Learn how to add interactivity to your web pages with JavaScript.

  • DOM manipulation
  • Event handling
  • Making API requests

Connecting to Your API

Learn how to connect your frontend to your backend API.

  • Making API requests with Fetch
  • Handling responses
  • Error handling

Guided Project

In the guided project for this module, you'll apply what you've learned about web development to create a frontend for your Learn and Be Curious project.

Project: Building a Web UI for Your Project

This project will guide you through creating a web interface that connects to your backend API.

Design Document - Frontend Mockups

Update the pages section of your design document with mockups of your web UI.

Additional Resources

MDN Web Docs

Comprehensive documentation for web technologies.

CSS Tricks

Tutorials and techniques for CSS.

JavaScript.info

Modern JavaScript tutorial.