Build an interactive to-do list
1. HTML Structure
The HTML will consist of the basic layout for the to-do list. We’ll need an input field, a button to add new tasks, and a list to display the tasks.
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>To-Do List</title>
<link rel=”stylesheet” href=”styles.css”>
</head>
<body>
<div class=”todo-container”>
<h1>My To-Do List</h1>
<input type=”text” id=”taskInput” placeholder=”Enter a new task”>
<button id=”addTaskButton”>Add Task</button>
<ul id=”taskList”></ul>
</div>
<script src=”script.js”></script>
</body>
</html>
2. CSS Styling
The CSS will style the to-do list, making it visually appealing.
/* styles.css */
body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.todo-container {
background-color: #fff;
padding: 20px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
border-radius: 8px;
width: 300px;
}
h1 {
text-align: center;
}
input, button {
width: 100%;
padding: 10px;
margin: 5px 0;
border: 1px solid #ccc;
border-radius: 4px;
}
button {
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
ul {
list-style-type: none;
padding-left: 0;
}
li {
background-color: #f1f1f1;
margin: 5px 0;
padding: 10px;
border-radius: 4px;
display: flex;
justify-content: space-between;
align-items: center;
}
li.done {
text-decoration: line-through;
color: #888;
}
.delete {
background-color: #ff4d4d;
color: white;
border: none;
border-radius: 4px;
padding: 5px;
cursor: pointer;
}
3. JavaScript Functionality
Now, let’s implement the functionality to add tasks, mark them as complete, and delete tasks.
// script.js
// Get references to DOM elements
const taskInput = document.getElementById(‘taskInput’);
const addTaskButton = document.getElementById(‘addTaskButton’);
const taskList = document.getElementById(‘taskList’);
// Function to create a new task item
function createTask(taskContent) {
// Create list item
const taskItem = document.createElement(‘li’);
// Create a text node for the task content
const taskText = document.createElement(‘span’);
taskText.textContent = taskContent;
taskItem.appendChild(taskText);
// Create a delete button
const deleteButton = document.createElement(‘button’);
deleteButton.textContent = ‘Delete’;
deleteButton.classList.add(‘delete’);
taskItem.appendChild(deleteButton);
// Append the task item to the task list
taskList.appendChild(taskItem);
// Mark task as done when clicked
taskItem.addEventListener(‘click’, () => {
taskItem.classList.toggle(‘done’);
});
// Delete task when delete button is clicked
deleteButton.addEventListener(‘click’, (event) => {
event.stopPropagation(); // Prevent the click event from propagating to taskItem
taskList.removeChild(taskItem);
});
}
// Add task when the button is clicked
addTaskButton.addEventListener(‘click’, () => {
const taskContent = taskInput.value.trim();
if (taskContent) {
createTask(taskContent);
taskInput.value = ”; // Clear the input field
}
});
// Optionally, allow the user to press Enter to add a task
taskInput.addEventListener(‘keypress’, (event) => {
if (event.key === ‘Enter’) {
addTaskButton.click();
}
});
4. How It Works:
- HTML: We set up the basic structure for the to-do list, including an input field for entering tasks, a button to add tasks, and a list to display them.
- CSS: Provides a simple yet attractive design. Tasks are styled with a background color, padding, and margins. We also added hover effects and styles for completed tasks.
- JavaScript: The script manages the core functionality:
- Adding tasks: When the “Add Task” button is clicked or Enter is pressed, the task is added to the list.
- Marking tasks as complete: Clicking on a task toggles its completion, applying a line-through effect.
- Deleting tasks: The “Delete” button beside each task allows the user to remove the task from the list.
5. Improvement Ideas:
- Persistent Storage: Save the tasks to localStorage so they persist after refreshing the page.
- Editing Tasks: Allow users to edit task content after it has been added.
- Styling Enhancements: Add icons or animations to improve the UX.
Recap:
You’ve now built a functional interactive to-do list that allows users to:
- Add tasks
- Mark tasks as complete
- Delete tasks
This is a great starting point for learning about JavaScript event handling, DOM manipulation, and user interactions.
Form Validation
Form validation is an essential process to ensure that the data submitted by the user is in the correct format and meets the expected criteria. It can be done both on the client-side (using JavaScript) and server-side (on the server after the form is submitted). Here, we’ll focus on client-side form validation using JavaScript.
1. Basic Form Structure (HTML)
Here is an example of a simple form that asks for the user’s name, email, and password.
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Form Validation</title>
<link rel=”stylesheet” href=”styles.css”>
</head>
<body>
<div class=”form-container”>
<h2>Sign Up Form</h2>
<form id=”signupForm”>
<label for=”name”>Name:</label>
<input type=”text” id=”name” name=”name” required>
<span class=”error” id=”nameError”></span>
<label for=”email”>Email:</label>
<input type=”email” id=”email” name=”email” required>
<span class=”error” id=”emailError”></span>
<label for=”password”>Password:</label>
<input type=”password” id=”password” name=”password” required>
<span class=”error” id=”passwordError”></span>
<button type=”submit”>Submit</button>
</form>
</div>
<script src=”script.js”></script>
</body>
</html>
2. Basic CSS Styling
We will style the form and error messages to make them more visually distinct.
/* styles.css */
body {
font-family: Arial, sans-serif;
background-color: #f8f9fa;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.form-container {
background-color: #fff;
padding: 20px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
width: 300px;
border-radius: 8px;
}
h2 {
text-align: center;
}
label {
display: block;
margin: 10px 0 5px;
}
input {
width: 100%;
padding: 10px;
margin-bottom: 15px;
border: 1px solid #ccc;
border-radius: 4px;
}
button {
background-color: #4CAF50;
color: white;
width: 100%;
padding: 10px;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
.error {
color: red;
font-size: 12px;
}
3. JavaScript for Form Validation
Now, let’s implement JavaScript to validate the form before submission.
// script.js
// Get form and input elements
const form = document.getElementById(‘signupForm’);
const nameInput = document.getElementById(‘name’);
const emailInput = document.getElementById(’email’);
const passwordInput = document.getElementById(‘password’);
// Get error display elements
const nameError = document.getElementById(‘nameError’);
const emailError = document.getElementById(’emailError’);
const passwordError = document.getElementById(‘passwordError’);
// Validate name
function validateName() {
if (nameInput.value.trim() === ”) {
nameError.textContent = ‘Name is required.’;
return false;
} else {
nameError.textContent = ”;
return true;
}
}
// Validate email using regular expression (Regex)
function validateEmail() {
const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (!emailPattern.test(emailInput.value)) {
emailError.textContent = ‘Please enter a valid email address.’;
return false;
} else {
emailError.textContent = ”;
return true;
}
}
// Validate password (min 8 characters)
function validatePassword() {
if (passwordInput.value.length < 8) {
passwordError.textContent = ‘Password must be at least 8 characters long.’;
return false;
} else {
passwordError.textContent = ”;
return true;
}
}
// Form submission handler
form.addEventListener(‘submit’, function(event) {
// Prevent form submission if any field is invalid
event.preventDefault();
// Validate all fields
const isNameValid = validateName();
const isEmailValid = validateEmail();
const isPasswordValid = validatePassword();
// If all fields are valid, submit the form
if (isNameValid && isEmailValid && isPasswordValid) {
alert(‘Form submitted successfully!’);
form.reset(); // Reset form fields
}
});
// Event listeners for real-time validation
nameInput.addEventListener(‘input’, validateName);
emailInput.addEventListener(‘input’, validateEmail);
passwordInput.addEventListener(‘input’, validatePassword);
4. How the Validation Works:
1. Validate Name:
- If the name field is empty, an error message will appear saying “Name is required.”
2. Validate Email:
- Uses a regular expression to ensure the email is in a valid format (e.g., someone@example.com).
3. Validate Password:
- Checks if the password is at least 8 characters long. If not, an error message will prompt the user.
4. Form Submission:
When the form is submitted, we prevent its default action (actual submission) using event.preventDefault(). Then, each field is validated, and if any validation fails, the corresponding error message is shown. Only if all fields are valid will the form be submitted (or we show a success alert in this case).
5. Additional Validation Tips:
- Client-Side vs Server-Side Validation: While client-side validation enhances user experience by catching errors before submission, server-side validation is still critical for security, as users can bypass client-side checks.
- Real-time Feedback: As seen in this example, real-time validation (while the user is typing) improves user experience by guiding them immediately when they enter incorrect data.
- Regex: Regular expressions are powerful for validating emails, phone numbers, and more. You can find more complex patterns for various use cases.
Recap:
- You’ve now built a simple form validation system that:
- Validates user input for Name, Email, and Password.
- Provides real-time and on-submit error messages.
- Prevents form submission if the data is invalid.
- This basic setup can be extended with additional features like:
- Confirm password field for matching.
- Password strength validation (e.g., include uppercase, numbers).
- More complex error handling (e.g., AJAX error responses).
Simple Calculator
A simple calculator allows users to perform basic arithmetic operations like addition, subtraction, multiplication, and division. It takes input from users, processes the operation when buttons are clicked, and displays the result.
1. Basic HTML Structure
Create the interface: display screen and buttons.
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1″>
<title>Simple Calculator</title>
<link rel=”stylesheet” href=”style.css”>
</head>
<body>
<div class=”calculator”>
<input type=”text” id=”display” disabled>
<div class=”buttons”>
<button onclick=”clearDisplay()”>C</button>
<button onclick=”appendCharacter(‘/’)”>/</button>
<button onclick=”appendCharacter(‘*’)”>*</button>
<button onclick=”deleteLast()”>⌫</button>
<button onclick=”appendCharacter(‘7’)”>7</button>
<button onclick=”appendCharacter(‘8’)”>8</button>
<button onclick=”appendCharacter(‘9’)”>9</button>
<button onclick=”appendCharacter(‘-‘)”>-</button>
<button onclick=”appendCharacter(‘4’)”>4</button>
<button onclick=”appendCharacter(‘5’)”>5</button>
<button onclick=”appendCharacter(‘6’)”>6</button>
<button onclick=”appendCharacter(‘+’)”>+</button>
<button onclick=”appendCharacter(‘1’)”>1</button>
<button onclick=”appendCharacter(‘2’)”>2</button>
<button onclick=”appendCharacter(‘3’)”>3</button>
<button onclick=”calculate()”>=</button>
<button onclick=”appendCharacter(‘0’)” class=”zero”>0</button>
<button onclick=”appendCharacter(‘.’)”>.</button>
</div>
</div>
<script src=”script.js”></script>
</body>
</html>
2. Basic CSS Styling
Simple styling for layout and visual design.
/* style.css */
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background: #e3f2fd;
margin: 0;
}
.calculator {
background: #fff;
padding: 20px;
border-radius: 15px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
#display {
width: 100%;
height: 50px;
margin-bottom: 10px;
text-align: right;
font-size: 1.5rem;
padding: 10px;
border: 1px solid #ccc;
border-radius: 8px;
}
.buttons {
display: grid;
grid-template-columns: repeat(4, 70px);
gap: 10px;
}
button {
padding: 15px;
font-size: 1.2rem;
border: none;
background-color: #90caf9;
border-radius: 8px;
cursor: pointer;
}
button:hover {
background-color: #64b5f6;
}
.zero {
grid-column: span 2;
}
3. JavaScript for Calculator Logic
The code handles button clicks, operations, and results.
// script.js
// Get the display element
const display = document.getElementById(‘display’);
// Function to append a character (number/operator)
function appendCharacter(character) {
display.value += character;
}
// Function to clear the display
function clearDisplay() {
display.value = ”;
}
// Function to delete the last character
function deleteLast() {
display.value = display.value.slice(0, -1);
}
// Function to calculate the result
function calculate() {
try {
display.value = eval(display.value);
} catch (error) {
alert(‘Invalid Expression’);
}
}
4. How This Calculator Works
- Display (input): Shows the current expression or result.
- Button Clicks: Numbers and operators are appended to the display.
- Clear (C): Empties the display completely.
- Backspace (⌫): Deletes the last character from the display.
- Equals (=): Evaluates the full mathematical expression using eval() and shows the result.
- Error Handling: If the expression is invalid (e.g., wrong syntax), an alert appears.
5. Important Notes
- Eval() is easy but not safe for real-world apps (it executes any JavaScript code).
- In production, it’s better to parse and evaluate the expression manually or use a library.
- Always validate input if you extend this calculator!
Example:
- Click 5
- Click +
- Click 7
- Click =
- Output → 12
Weather app using API
A Weather App allows users to input a city name and fetch real-time weather data (like temperature, condition, humidity) from a public API (like OpenWeatherMap) and display it cleanly.
1. Setup: Basic HTML Structure
Create a simple input field, search button, and an area to show weather information.
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1″>
<title>Weather App</title>
<link rel=”stylesheet” href=”style.css”>
</head>
<body>
<div class=”weather-app”>
<h1>Weather Checker</h1>
<input type=”text” id=”cityInput” placeholder=”Enter city name”>
<button onclick=”getWeather()”>Search</button>
<div class=”weather-info” id=”weatherInfo”>
<!– Weather results will be inserted here –>
</div>
</div>
<script src=”script.js”></script>
</body>
</html>
2. Basic CSS Styling
Style the app to make it visually appealing.
/* style.css */
body {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background: linear-gradient(#74ebd5, #ACB6E5);
margin: 0;
font-family: Arial, sans-serif;
}
.weather-app {
text-align: center;
background: #fff;
padding: 30px;
border-radius: 15px;
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
input, button {
padding: 10px;
margin: 10px;
border: none;
border-radius: 8px;
font-size: 1rem;
}
button {
background-color: #4fc3f7;
color: #fff;
cursor: pointer;
}
button:hover {
background-color: #039be5;
}
.weather-info {
margin-top: 20px;
font-size: 1.2rem;
}
3. JavaScript: Fetching Weather Data
Use JavaScript to connect to the API, fetch weather, and display it.
// script.js
const apiKey = ‘YOUR_API_KEY’; // Replace with your actual OpenWeatherMap API key
async function getWeather() {
const city = document.getElementById(‘cityInput’).value;
const weatherInfo = document.getElementById(‘weatherInfo’);
if (!city) {
weatherInfo.innerHTML = `<p>Please enter a city name.</p>`;
return;
}
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(‘City not found’);
}
const data = await response.json();
const temperature = data.main.temp;
const description = data.weather[0].description;
const humidity = data.main.humidity;
const windSpeed = data.wind.speed;
weatherInfo.innerHTML = `
<h2>${data.name}, ${data.sys.country}</h2>
<p><strong>Temperature:</strong> ${temperature} °C</p>
<p><strong>Condition:</strong> ${description}</p>
<p><strong>Humidity:</strong> ${humidity}%</p>
<p><strong>Wind Speed:</strong> ${windSpeed} m/s</p>
`;
} catch (error) {
weatherInfo.innerHTML = `<p>Error: ${error.message}</p>`;
}
}
4. How This App Works
- User Input: User types a city name and clicks “Search.”
- API Request: The app sends a GET request to OpenWeatherMap’s API with the city name and your API key.
- Data Parsing: Receives weather data like temperature, condition, humidity, and wind speed.
- Display: The data is inserted into the HTML dynamically using JavaScript.
- Error Handling: If the city isn’t found or there’s a network error, a user-friendly message is shown.
5. Important Points
- API Key: You must sign up at OpenWeatherMap and get a free API key.
- Security: Never expose API keys in production. Use a backend if needed.
Enhancements:
- Add weather icons.
- Add loading spinners.
- Handle edge cases (e.g., empty input, invalid city).
- Convert temperature units (°C/°F toggle).
Example Walkthrough:
- Type “London” → Click Search
- App fetches data like:
- Temperature: 15°C
- Condition: Clear sky
- Humidity: 60%
- Wind Speed: 3.5 m/s
- Data shows instantly inside your web page.
DOM-based mini-projects
There are many steps of DOM-Based Mini-Projects
1. To-Do List App
- Concept: Add, delete, and mark tasks as complete.
- Key DOM skills: createElement, appendChild, removeChild, classList.toggle, event delegation.
- Enhancements: Save tasks in localStorage, filter tasks (all/active/completed).
2. Interactive Counter
- Concept: Increase, decrease, or reset a counter value.
- Key DOM skills: Event listeners (click), text content manipulation (innerText or textContent).
- Enhancements: Color change based on positive or negative value.
3. Accordion Component
- Concept: Expand and collapse sections when clicked.
- Key DOM skills: classList.toggle, querySelectorAll, event bubbling.
- Enhancements: Allow only one section to open at a time (single open accordion).
4. Image Slider/Carousel
- Concept: Cycle through images manually (next/prev buttons) or automatically.
- Key DOM skills: src attribute manipulation, event listeners, setInterval.
- Enhancements: Add animation transitions, thumbnails preview.
5. Modal Popup
- Concept: Open and close a modal window with a button click.
- Key DOM skills: classList.add/remove, addEventListener, keydown events (ESC to close).
- Enhancements: Click outside the modal to close, trap focus inside modal for accessibility.
6. Live Character Counter
- Concept: Show the number of characters typed into a textarea.
- Key DOM skills: input event, value property, updating DOM elements live.
- Enhancements: Warn when reaching a character limit.
7. Password Show/Hide Toggle
- Concept: Toggle password visibility in an input field.
- Key DOM skills: type attribute manipulation, addEventListener.
- Enhancements: Add an eye icon toggle.
8. Theme Switcher (Dark/Light Mode)
- Concept: Switch website themes dynamically.
- Key DOM skills: classList.toggle, changing CSS variables via JavaScript.
- Enhancements: Save user’s choice in localStorage.
9. Form Validation
- Concept: Validate input fields (e.g., email, password strength) before submission.
- Key DOM skills: submit event, preventDefault(), input event, dynamic error messages.
- Enhancements: Real-time validation, highlight valid/invalid fields.
10. Drag and Drop List
- Concept: Rearrange list items by dragging and dropping.
- Key DOM skills: dragstart, dragover, drop, manipulating DOM positions.
- Enhancements: Save new order to local storage.
11. Quiz Application
- Concept: Display a series of questions and evaluate answers.
- Key DOM skills: Dynamically rendering questions, handling form submissions, scoring.
- Enhancements: Timer countdown, high score board.
12. Random Joke Generator
- Concept: Fetch and display a random joke with a button click.
- Key DOM skills: fetch API, DOM update with fetched data.
- Enhancements: Loading spinner while fetching, error handling.
13. Countdown Timer
- Concept: Countdown to a specific date/time.
- Key DOM skills: setInterval, DOM updates every second.
- Enhancements: Display different messages when the countdown ends.
14. Typing Speed Test
- Concept: Measure how fast the user types a given sentence.
- Key DOM skills: keydown, timer control, dynamic text checking.
- Enhancements: Highlight mistakes, leaderboard system.
15. Weather App (API Project)
- Concept: Enter a city name and display weather info.
- Key DOM skills: fetch API, dynamically inserting fetched JSON data.
- Enhancements: Add weather icons, error messages for invalid city names.
Would you like me to also suggest:
- A recommended order (easy ➔ hard)?
- Or starter templates for any of these projects?