
Web Prototyping: Sketches, Wireframes, Mockups, and Prototypes
03/12/2026
After completing the basic JavaScript tutorial (in Spanish) and the JavaScript events and DOM tutorial (in Spanish), put what you learned into practice to reinforce it. These worked exercises range from the basics to more advanced challenges with events and DOM interaction.
These exercises give you practical, realistic examples of how to apply JavaScript. They are grouped by topic and difficulty. Let’s get started!
1. Worked exercises for basic JavaScript
Try these worked exercises after completing the basic JavaScript tutorial.
1.1. Travel expense calculator
Write a program that calculates the total cost of a trip, including accommodation, food, and entertainment.
- Ask the user to enter the estimated expenses for each category.
- Calculate the total by adding all the expenses.
- Show the total cost to the user.
- Example input: Accommodation €200, food €150, entertainment €100.
- Expected output: The trip costs €450.
Solution:
let alojamiento = parseFloat(prompt("Enter the estimated accommodation cost: "));
let alimentacion = parseFloat(prompt("Enter the estimated food cost: "));
let entretenimiento = parseFloat(prompt("Enter the estimated entertainment cost: "));
let costeTotal = alojamiento + alimentacion + entretenimiento;
alert("The trip costs: " + costeTotal.toFixed(2) + "€");
1.2. Dog age calculator
Create a program that converts a dog’s age to human years.
- Ask the user for their dog’s age in years.
- Calculate the dog’s age in human years by multiplying its age by 7.
- Show the dog’s age in human years.
- Example input: Dog’s age: 5 years.
- Expected output: The dog’s age in human years is 35 years.
The familiar rule multiplies a dog’s age by seven, assuming that one dog year is roughly equivalent to seven human years in terms of aging. It gives a rough estimate, as dogs age at different rates depending on factors such as their breed and size.
Solution:
let edadPerro = parseInt(prompt("Enter your dog’s age in years: "));
let edadHumana = edadPerro * 7;
console.log("Your dog’s age in human years is: " + edadHumana + " years");
1.3. Body mass index (BMI) calculator
Create a program that calculates a person’s body mass index (BMI) from their weight and height.
- Ask the user to enter their weight in kilograms and height in meters.
- Calculate BMI by dividing their weight by their height squared.
- Display the BMI and its category according to the BMI ranges.
- Example input: Weight: 70 kg, height: 1.75 m.
- Expected output: BMI: 22.86, category: normal weight.
Body mass index (BMI) is calculated by dividing weight in kilograms by height in meters squared. It gives an estimate of body fat and is used to classify weight as underweight, normal weight, overweight, or obesity.
Solution:
let peso = parseFloat(prompt("Enter your weight in kilograms: "));
let altura = parseFloat(prompt("Enter your height in meters: "));
let imc = peso / (altura * altura);
console.log("Your BMI is: " + imc.toFixed(2));
if (imc < 18.5) {
console.log("Category: Underweight");
} else if (imc >= 18.5 && imc < 25) {
console.log("Category: Normal weight");
} else if (imc >= 25 && imc < 30) {
console.log("Category: Overweight");
} else {
console.log("Category: Obesity");
}
1.4. Discount calculator
Create a program that calculates the final price of a product after a discount.
- Ask the user to enter the product’s original price.
- Ask for the discount percentage, for example 10 for a 10% discount.
- Use a function to calculate the final price after applying the discount.
- Display the final price.
Example input:
Enter the product’s original price: 50
Enter the discount percentage: 20.
Expected output: After a 20% discount, the final price is €40.
Solution:
// Define the function that calculates the final discounted price
function calcularPrecioFinal(precioOriginal, descuento) {
// Calculate the discount amount
let cantDescuento = (precioOriginal * descuento) / 100;
// Subtract the discount from the original price
let precioFinal = precioOriginal - cantDescuento;
// Return the final price rounded to two decimal places
return precioFinal.toFixed(2);
}
// Ask for the original price
let precioOriginal = parseFloat(prompt("Enter the original price:"));
// Ask for the discount percentage
let descuento = parseFloat(prompt("Enter the discount percentage:"));
// Call calcularPrecioFinal to calculate the final price
let precioFinal = calcularPrecioFinal(precioOriginal, descuento);
// Show the final price
alert("The final price after a " + descuento + "% discount is: " + precioFinal + " euros.");
1.5. Prime number generator
Write a program that asks the user for two numbers and displays all prime numbers between them, including the endpoints.
- Ask the user to enter two integers.
- Find all the prime numbers in the range, including the endpoints.
- Example input: First number: 10, second number: 20.
- Expected output: The prime numbers between 10 and 20 are 11, 13, 17, and 19.
A prime number is a natural number greater than 1 with exactly two positive divisors, 1 and itself. For example, 2, 3, 5, and 7 are prime numbers.
Solution:
// Check whether a number is prime
function esPrimo(num) {
if (num <= 1) return false; // Numbers at or below 1 are not prime
// Check divisibility by each integer from 2 through the square root
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) return false; // A divisible number is not prime
}
return true; // If no divisor was found, the number is prime
}
// Ask for the range endpoints
let inicio = parseInt(prompt("Enter the first number in the range:"));
let fin = parseInt(prompt("Enter the last number in the range:"));
// Show primes in the range
console.log("Prime numbers between", inicio, "and", fin, ":");
for (let i = inicio; i <= fin; i++) {
if (esPrimo(i)) {
console.log(i);
}
}
1.6. Fibonacci sequence generator
Create a program that generates the first N terms of the Fibonacci sequence, where the user supplies N.
- Ask how many terms of the Fibonacci sequence to generate.
- Use a function to calculate the sequence.
- Show the user the first N terms.
- Example input: Number of terms: 8.
- Expected output: The first eight terms are 0, 1, 1, 2, 3, 5, 8, and 13.
The Fibonacci sequence starts with 0 and 1. Each subsequent term is the sum of the two preceding terms.
Solution:
// Generate the first N terms of the Fibonacci sequence
function fibonacci(n) {
let sequence = [0, 1];
for (let i = 2; i < n; i++) {
sequence.push(sequence[i - 1] + sequence[i - 2]);
}
return sequence;
}
// Ask how many terms to generate
let numTerms = parseInt(prompt("Enter the number of Fibonacci terms to generate:"));
// Check that the user entered a valid number
if (!isNaN(numTerms) && numTerms > 0) {
console.log(`The first ${numTerms} Fibonacci terms are: ${fibonacci(numTerms).join(', ')}`);
} else {
console.error("Error: Enter a valid number greater than zero.");
}
1.7. Temperature converter
Create a program that converts a temperature from Celsius to Fahrenheit or vice versa, according to the user’s choice.
- Ask the user to choose the conversion direction.
- Ask for the temperature to convert.
- Use functions to perform the conversions.
- Show the result of the conversion.
- Example input: Choose 1 for Celsius to Fahrenheit or 2 for the reverse. Enter 1, then enter 25 degrees Celsius.
- Expected output: 25 degrees Celsius equals 77 degrees Fahrenheit.
Celsius to Fahrenheit: Multiply by 9/5 and add 32. °F = (°C × 9/5) + 32.
Fahrenheit to Celsius: Subtract 32 and multiply by 5/9. °C = (°F − 32) × 5/9.
Solution:
// Convert Celsius to Fahrenheit
function celsiusToFahrenheit(celsius) {
return (celsius * 9/5) + 32;
}
// Convert Fahrenheit to Celsius
function fahrenheitToCelsius(fahrenheit) {
return (fahrenheit - 32) * 5/9;
}
// Main program function
function temperaturaConversor() {
// Ask for the conversion direction
let opcion = prompt("Choose a conversion: 1 for Celsius to Fahrenheit, 2 for Fahrenheit to Celsius.");
// Convert the choice to an integer
opcion = parseInt(opcion);
// Validate the user’s choice
if (opcion !== 1 && opcion !== 2) {
alert("Invalid choice. Enter 1 or 2.");
return;
}
// Ask for the temperature to convert
let temperatura = prompt("Enter the temperature:");
// Convert the temperature to a floating-point number
temperatura = parseFloat(temperatura);
// Convert in the selected direction
let resultado;
if (opcion === 1) {
resultado = celsiusToFahrenheit(temperatura);
alert(`${temperatura} degrees Celsius equals ${resultado} degrees Fahrenheit.`);
} else {
resultado = fahrenheitToCelsius(temperatura);
alert(`${temperatura} degrees Fahrenheit equals ${resultado} degrees Celsius.`);
}
}
// Call the main program function
temperaturaConversor();
1.8. Calculate a factorial
Write a program that calculates the factorial of a nonnegative integer entered by the user.
- Define a function called
calculateFactorialwith a parameternumberfor the number whose factorial you want to calculate. - Use a
forloop inside the function to calculate the factorial. - Initialize
resultto 1 because both 0! and 1! equal 1. - Loop from 1 through
number, multiplyingresultby the current value on each iteration and storing the new value inresult. - Return
resultat the end of the function. - Ask the user to enter a nonnegative integer.
- Convert the user’s input to an integer with
parseInt. - Call
calculateFactorialwith the number entered and show the result.
The factorial of a positive integer n, written n!, is the product of all positive integers from 1 through n. The formula is n! = n × (n − 1) × (n − 2) × … × 1. By definition, 0! = 1.
Solution:
// Define the function that calculates the factorial
function calculateFactorial(number) {
let result = 1;
for (let i = 1; i <= number; i++) {
result *= i;
}
return result;
}
// Ask the user for an integer
let userInput = prompt("Enter a nonnegative integer to calculate its factorial:");
// Convert the input to an integer
let number = parseInt(userInput);
// Check that the input is a nonnegative integer
if (!isNaN(number) && number >= 0) {
// Call the function to calculate the factorial and display the result
let factorial = calculateFactorial(number);
console.log(`The factorial of ${number} is: ${factorial}`);
} else {
console.log("Invalid input. Enter a nonnegative integer.");
}
2. Worked JavaScript exercises: Events and the DOM
These worked exercises are designed to follow the JavaScript Events and DOM tutorial (in Spanish).
2.1. Show and hide an element with JavaScript
Implement the JavaScript that toggles the visibility of the box when someone clicks the button.
Instructions:
Use the supplied HTML, which contains a box and a button.
<div id="container">
<div id="box"></div>
<button id="toggleBtn">Hide box</button>
</div>
Use the supplied CSS to style the elements. You do not need to modify it.
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
margin: 0;
background-color: #f4f4f4;
}
#container {
text-align: center;
}
#box {
width: 100px;
height: 100px;
background-color: #3498db;
margin: 20px auto;
}
button {
margin: 10px;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
background-color: #2ecc71;
color: #fff;
font-size: 16px;
transition: background-color 0.3s;
}
button:hover {
background-color: #27ae60;
}
Steps:
- Create a function called
toggleBoxthat runs when the button is clicked. Toggle the box by switching thedisplayproperty between'none'and'block'. - The function should also switch the button label between “Hide box” and “Show box” as appropriate.
Add a click event listener to the button that calls toggleBox.
Check that the program works. Clicking the button should hide or show the box, depending on its current state, and update the button label accordingly.
Solution on CodePen (original demo in Spanish):
2.2. Display random phrases with JavaScript
You are given HTML and CSS for a container that displays random phrases from an array when the user clicks a button. Write the JavaScript so that clicking the button in the example displays a random phrase from the frasesFrikisInformatica array.

HTML code:
<div id="contenido-informatica"> <p id="texto-informatica">Algorithm: what programmers say when they don’t want to explain what they did.</p> <button id="ver-mas-boton">Show another phrase</button> </div>
CSS code:
#contenido-informatica {
background-color: #f5f5f5;
border-radius: 10px;
padding: 20px;
box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);
text-align: center;
max-width: 400px;
margin: 0 auto;
}
#texto-informatica {
font-size: 18px;
color: #333;
margin-bottom: 20px;
}
#ver-mas-boton {
background-color: #007bff;
color: #fff;
border: none;
border-radius: 5px;
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
transition: background-color 0.3s ease;
}
#ver-mas-boton:hover {
background-color: #0056b3;
}
Solution on CodePen (original demo in Spanish):
2.3. Add tasks to a list with JavaScript
Implement the feature that adds tasks to a list when the “Add task” button is clicked.

Instructions:
- Use the supplied HTML. It contains an input for new tasks, a button to add them, and a list (
ul) to display them.
<div id="taskContainer">
<h1>Task list</h1>
<div class="inputContainer">
<input type="text" id="newTaskInput" placeholder="Enter a new task">
<button id="addTaskBtn">Add task</button>
</div>
<ul id="taskList">
<!-- Tasks will be added here -->
</ul>
</div>
- Use the supplied CSS to style the elements.
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
margin: 20px;
}
#taskContainer {
width: 400px;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
padding: 20px;
}
h1 {
text-align: center;
}
.inputContainer {
display: flex;
align-items: center;
margin-bottom: 10px;
}
input[type="text"] {
flex: 1;
padding: 10px;
margin-right: 10px;
border: 1px solid #ccc;
border-radius: 5px;
font-size: 16px;
}
button {
padding: 10px 20px;
background-color: #4caf50;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
transition: background-color 0.3s;
}
button:hover {
background-color: #45a049;
}
ul {
list-style-type: none;
padding: 0;
}
li {
padding: 10px;
border-bottom: 1px solid #eee;
display: flex;
justify-content: space-between;
align-items: center;
}
li:last-child {
border-bottom: none;
}
.deleteBtn {
background-color: #dc3545;
color: #fff;
border: none;
border-radius: 5px;
padding: 5px 10px;
cursor: pointer;
transition: background-color 0.3s;
}
.deleteBtn:hover {
background-color: #d32f2f;
}
- Complete the JavaScript to add tasks to the list when the “Add task” button is clicked.
// Select DOM elements
const newTaskInput = document.getElementById('newTaskInput');
const addTaskBtn = document.getElementById('addTaskBtn');
const taskList = document.getElementById('taskList');
// Function to add a new task
function addTask() {
//Add your JavaScript here
}
// Attach a click handler to the add task button
addTaskBtn.addEventListener('click', addTask);
- Clear the text field each time a task is added.
- Each new task must have an “X” button that removes that task when clicked.
Steps:
- Select the DOM elements you need: the new task input, the add task button, and the task list.
- Create an
addTaskfunction that runs when the add task button is clicked. - Inside
addTask:- Read the value of the new task input.
- Check that the text field is not empty.
- If the field contains text:
- Create a list item (
li) and set its text to the value entered for the new task. - Create a
buttonlabeled “X” to remove the task. - Attach a click handler that removes the corresponding task.
- Give the remove button the
deleteBtnclass. - Append the remove button to the list item.
- Append the list item to the task list.
- Clear the text field.
- Attach a click listener to the add task button that calls
addTask.
Solution on CodePen (original demo in Spanish):
2.4. Pick a random name with JavaScript
You are given HTML and CSS for a form that accepts the names of people or things. Write the JavaScript to add names to a list and then pick one at random, as shown below.

Instructions:
Use the supplied HTML, which includes a field for entering names, a button to add them, and a list to display them.
<div id="container"> <h1>Random selection</h1> <input type="text" id="inputName" placeholder="Enter a name"> <button id="addBtn">Add</button> <ul id="nameList"></ul> <button id="randomBtn">Pick at random</button> </div>
Use the supplied CSS to style the elements. You do not need to modify it.
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
margin: 0;
background-color: #f9f9f9;
}
#container {
text-align: center;
background-color: #fff;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
padding: 20px;
margin: 20px;
}
h1 {
margin-top: 0;
color: #333;
}
input[type="text"] {
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
font-size: 16px;
margin-bottom: 10px;
width: 200px;
}
button {
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
background-color: #4caf50;
color: #fff;
font-size: 16px;
margin: 10px;
transition: background-color 0.3s;
}
button:hover {
background-color: #45a049;
}
ul {
list-style: none;
padding: 0;
margin-top: 20px;
text-align: left;
}
li {
padding: 10px;
border-bottom: 1px solid #eee;
}
li:last-child {
border-bottom: none;
}
.randomBtn {
background-color: #2196f3;
}
.randomBtn:hover {
background-color: #1e87db;
}
.selected {
background-color: #ffff00;
}
.selected:hover {
background-color: #ffff00;
}
Steps:
- Listen for clicks on the “Add” button. Call a function that reads the input value, adds the name to an in-memory list, and updates the list displayed in the DOM.
- Write a function to render the names. It should update the
<ul>with the names stored in memory. - Listen for clicks on the “Pick at random” button. Pick a random name from the list in memory, highlight it in the displayed list, and show a message naming the selection.
Check the result. Clicking “Pick at random” should highlight one name and display a message saying it was chosen at random.
Solution on CodePen (original demo in Spanish):
3. Unsolved JavaScript exercises
Practice what you have learned by completing the following JavaScript exercises.
3.1. Unsolved exercises on basic JavaScript
These exercises follow the sections of the basic JavaScript tutorial (in Spanish).
3.1.1. Exercise 1: Data types (sections 1–6)
Primitive data types:
1.1. Declare a string variable, assign it a greeting, and print it to the console.
1.2. Declare a number variable, assign it your age, and print it to the console.
1.3. Declare a Boolean variable and assign it true or false. Print it to the console.
1.4. Declare a variable set to null and another set to undefined. Print both to the console.
Non-primitive types (objects):
1.5. Create an object representing an item with properties such as name, price, and category. Print it to the console.
1.6. Declare an array of city names and print it to the console.
Variables:
1.7. Assign your favorite color to a variable. Then assign it another color and print both values to the console.
Variable declarations:
1.8. Declare two variables, one without an assigned value and the other set to null. Print both to the console.
Variable scope:
1.9. Create a variable inside a function and another outside it. Try accessing both inside and outside the function, and observe the console results.
Variable naming rules:
1.10. Try names that follow JavaScript’s identifier rules and names that break them. Log the valid variables and observe what happens when you try the invalid declarations separately.
Operators:
1.11. Apply +, -, *, /, %, ++, and -- to numeric variables and print the results.
Strings:
1.12. Declare a multiline string using escape sequences such as \n and \t. Print the resulting string.
3.1.2. Exercise 2: Control structures (section 7)
Conditionals (if, else if, else):
2.1. Write a program that checks whether a number is positive, negative, or zero and prints the result.
2.2. Write a program that determines from a person’s age whether they are a minor, an adult, or an older adult.
Loops (for, while, do...while):
2.3. Use a for loop to print i from 0 to 4.
2.4. Use a while loop to print the counter from 0 to 4.
2.5. Use a do...while loop to print x from 0 to 4.
Loop control (break, continue):
2.6. Use break to stop a for loop when i is 3.
2.7. Use continue to skip the iteration of a for loop when j is 2.
Conditional (switch):
2.8. Ask the user for a number from 1 to 12 and display the corresponding month name.
Example:
- Enter a number from 1 to 12 to find the corresponding month: 9
- The month corresponding to 9 is September.
3.1.3. Exercise 3: Functions (section 8)
3.1. Ask the user for a circle’s radius, then calculate and display its area and circumference.
- Ask the user to enter the radius.
- Define two functions, one for the area and one for the circumference.
- Use π × radius² for the area and 2 × π × radius for the circumference.
- Call both functions with the radius entered by the user.
- Display the area and circumference.
3.2. Write a function named calculatePower that takes base and exponent and returns the base raised to that exponent.
Example:
// Call the function let result = calculatePower(2, 3); console.log(result); // Expected result: 8
3.1.4. Exercise 4: Arrays (section 9)
4.1. Write a program that asks the user to enter a list of numbers and finds the largest number in the list.
- Ask the user how many numbers they want to enter.
- Ask them to enter each number one at a time.
- Store the numbers in an array.
- Write a
findLargestNumberfunction that receives an array of numbers and returns the largest. - Inside the function, iterate through the array with a
forloop to find the largest number. - Show the largest number to the user.
Make sure the program uses an array to store the numbers and the function to find the largest one.
Example:
- Enter how many numbers: 5
- Enter number 1: 10
- Enter number 2: 25
- Enter number 3: 7
- Enter number 4: 18
- Enter number 5: 12
- The largest number is 25.
3.1.5. Exercise 5: The for loop (section 7)
5.1. The for loop
- Print the numbers from 20 to 30 to the console.
- Print the even numbers from 30 to 50 to the console.
- Calculate the sum of the first 50 natural numbers.
- Print the eight times table.
- Print the elements of an array.
- Print a triangle made of asterisks, nine rows high.
- Calculate the sum of even numbers from 1 to 50.
- Print the numbers from 30 down to 20 in descending order.
- Calculate the average of an array of numbers.
3.2. Unsolved exercises on JavaScript events and the DOM
3.2.1. Exam-style exercise: Display random phrases
You are given HTML, CSS, and JavaScript for a container that displays random phrases from an array when someone uses a button. Modify the JavaScript so that clicking the button in the example displays a random phrase from the frasesFrikisInformatica array.
HTML:
<div id="contenido-informatica"> <p id="texto-informatica">Algorithm: what programmers say when they don’t want to explain what they did.</p> <button id="ver-mas-boton">Show another phrase</button> </div>
CSS:
#contenido-informatica {
background-color: #f5f5f5;
border-radius: 10px;
padding: 20px;
box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);
text-align: center;
max-width: 400px;
margin: 0 auto;
}
#texto-informatica {
font-size: 18px;
color: #333;
margin-bottom: 20px;
}
#ver-mas-boton {
background-color: #007bff;
color: #fff;
border: none;
border-radius: 5px;
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
transition: background-color 0.3s ease;
}
#ver-mas-boton:hover {
background-color: #0056b3;
}
JavaScript:
// Define an array of computing quotes
var frasesFrikisInformatica = [
"Coffee is what fuels programmers.",
"Code comments are like personal hygiene: everyone says it matters, but few follow through.",
"Documentation is like sex: when it is good, it is very good; when it is bad, it is better than nothing.",
"Communication in computing is like talking to a programmer: do you speak English or code?",
"The cloud is more than a trend. It is a way of life!",
"Programming is like playing an out-of-tune piano: only the person playing understands it."
];
// Function to pick new text at random
function cambiarTexto() {
// Pick a random index from the array
var indice = Math.floor(Math.random() * frasesFrikisInformatica.length);
// Get the text element
// Use .textContent to replace the text with the selected phrase
}
document.addEventListener("DOMContentLoaded", function() {
// Attach an event listener to the button
});
3.2.2. Exam-style exercise: Change colors at random
Modify the previous code so that it changes both the text color and the button color at random, as well as displaying a random phrase. Define your own array of colors or start with the example below.
var colores = [ "#ff0000", // Red "#00ff00", // Green "#0000ff", // Blue "#ff00ff", // Magenta "#00ffff", // Cyan "#ff8000", // Orange "#8000ff", // Purple "#00ff80", // Light green "#ff0080", // Pink "#80ff00", // Lime green "#0080ff", // Light blue "#ffbf00", // Dark yellow "#bf00ff", // Dark violet "#00ffbf", // Turquoise "#bf00ff", // Purple "#00bfff", // Light blue "#ff00bf", // Dark magenta "#80ff80", // Pastel green "#ff80ff", // Pastel pink "#80ffff" // Light cyan ];
3.2.3. Exam-style exercise: Shopping list
You are given HTML and CSS for a shopping list like the one below.
Write the JavaScript needed to make the form work.
Instructions:
- Select the DOM elements you need: the input for new items, the button to add them, and the list where they will appear.
- Implement an
addItemfunction that runs when the “Add” button is clicked. It should do the following:- Read the input value and make sure it is not empty.
- Create a list item (
li) and set its content to the input value. - Create two buttons inside the new list item, one to mark it as complete and the other to delete it.
- Attach listeners to the complete and delete buttons.
- Append the new item to the list.
- Clear the input after adding the item.
- Attach
addItemto the “Add” button’s click event.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<title>Shopping list</title>
</head>
<body>
<div id="taskContainer">
<h1>Shopping list</h1>
<div class="inputContainer">
<input type="text" id="newItemInput" placeholder="Enter a new item">
<button id="addItemBtn">Add</button>
</div>
<ul id="itemsList">
<!-- Items will be added here -->
</ul>
</div>
<script src="script.js"></script>
</body>
</html>
CSS:
body {
font-family: Arial, sans-serif;
background-color: #f8f8f8;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
#taskContainer {
width: 400px;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
padding: 20px;
}
h1 {
text-align: center;
color: #FF5722;
}
.inputContainer {
display: flex;
align-items: center;
margin-bottom: 10px;
}
input[type="text"] {
flex: 1;
padding: 10px;
margin-right: 10px;
border: 1px solid #ccc;
border-radius: 5px;
font-size: 16px;
}
.inputContainer button {
padding: 10px;
background-color: #FF5722;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
transition: background-color 0.3s;
}
inputContainer button:hover {
background-color: #E64A19;
}
ul {
list-style-type: none;
padding: 0;
}
li {
padding: 10px;
border-bottom: 1px solid #eee;
display: flex;
align-items: center;
}
li:last-child {
border-bottom: none;
}
.completed {
text-decoration: line-through;
color: #999;
}
.completeBtn, .deleteBtn {
background-color: transparent;
border: none;
font-size: 16px;
cursor: pointer;
}
.completeBtn:hover, .deleteBtn:hover {
color: #FF5722;
}
.material-icons {
font-size: 24px;
color: black;
cursor: pointer;
transition: color 0.3s;
}
.material-icons:hover {
color: #FF5722;
}
.deleteBtn {
order: 3;
}
We hope these worked exercises have helped you strengthen your JavaScript skills. Working through them will reinforce what you know and prepare you for more complex web development problems.
Regular practice and a variety of problems are key to learning JavaScript. Revisit these exercises whenever you want to review a concept or improve your technique. You can also keep learning with our web design and development courses (in Spanish).