9 Commits

20 changed files with 363 additions and 332 deletions

View File

@@ -1 +1,10 @@
// Agregar aquí el código javascript // Agregar aquí el código javascript
document.getElementById('greet').addEventListener('click', () => {
const name = document.getElementById('name').value;
if (name.trim() === '') {
alert('Por favor, ingresa tu nombre.');
return;
}
document.getElementById('greeting').textContent = `¡Hola, ${name}!`;
});

View File

@@ -8,7 +8,10 @@
</head> </head>
<body> <body>
<h1>Ejercicio 1</h1> <h1>Ejercicio 1</h1>
<label for="name">Nombre:</label>
<input type="text" id="name" name="name">
<button id="greet">Saludar</button>
<p id="greeting"></p>
<script src="ejercicio1.js"></script> <script src="ejercicio1.js"></script>
</body> </body>
</html> </html>

View File

@@ -1 +1,15 @@
// Agregar aquí el código javascript // Agregar aquí el código javascript
document.getElementById('addTask').addEventListener('click', () => {
const taskInput = document.getElementById('task');
const task = taskInput.value.trim();
if (task === '') {
alert('Por favor, ingresa una tarea.');
return;
}
const taskList = document.getElementById('taskList');
const li = document.createElement('li');
li.textContent = task;
taskList.appendChild(li);
taskInput.value = '';
});

View File

@@ -8,7 +8,10 @@
</head> </head>
<body> <body>
<h1>Ejercicio 2</h1> <h1>Ejercicio 2</h1>
<label for="task">Crea una nueva tarea:</label>
<input type="text" id="task" name="task">
<button id="addTask">Agregar tarea</button>
<ul id="taskList"></ul>
<script src="ejercicio2.js"></script> <script src="ejercicio2.js"></script>
</body> </body>
</html> </html>

View File

@@ -1 +1,7 @@
// Agregar aquí el código javascript // Agregar aquí el código javascript
document.getElementById('itemList').addEventListener('click', (event) => {
if (event.target.tagName === 'LI') {
event.target.classList.toggle('selected');
}
});

View File

@@ -1,2 +1,5 @@
/* Agregar el código CSS necesario para el ejercicio */ /* Agregar el código CSS necesario para el ejercicio */
.selected {
background-color: lightblue;
}

View File

@@ -8,7 +8,14 @@
</head> </head>
<body> <body>
<h1>Ejercicio 3</h1> <h1>Ejercicio 3</h1>
<ul id="itemList">
<li>Elemento 1</li>
<li>Elemento 2</li>
<li>Elemento 3</li>
<li>Elemento 4</li>
<li>Elemento 5</li>
<li>Elemento 6</li>
</ul>
<script src="ejercicio3.js"></script> <script src="ejercicio3.js"></script>
</body> </body>
</html> </html>

View File

@@ -1 +1,33 @@
// Agregar aquí el código javascript // Agregar aquí el código javascript
const incrementButton = document.getElementById('increment');
const decrementButton = document.getElementById('decrement');
const counterDisplay = document.getElementById('counter');
let counter = 0;
incrementButton.addEventListener('click', () => {
if (counter >= 10) {
incrementButton.disabled = true;
alert('El contador ha alcanzado el valor máximo de 10.');
return;
}
counter++;
if (counter > 0) {
decrementButton.disabled = false;
}
counterDisplay.textContent = counter;
});
decrementButton.addEventListener('click', () => {
if (counter <= 0) {
decrementButton.disabled = true;
alert('El contador ha alcanzado el valor mínimo de 0.');
return;
}
counter--;
if (counter < 10) {
incrementButton.disabled = false;
}
counterDisplay.textContent = counter;
});

View File

@@ -8,7 +8,9 @@
</head> </head>
<body> <body>
<h1>Ejercicio 4</h1> <h1>Ejercicio 4</h1>
<p> Contador: <span id="counter">0</span></p>
<button id="increment">Incrementar</button>
<button id="decrement">Decrementar</button>
<script src="ejercicio4.js"></script> <script src="ejercicio4.js"></script>
</body> </body>
</html> </html>

View File

@@ -1 +1,45 @@
// Agregar aquí el código javascript // Agregar aquí el código javascript
const countries = [
'Argentina',
'Brasil',
'Chile',
'Colombia',
'Ecuador',
'Perú',
'Uruguay',
'Venezuela',
'Paraguay',
'Bolivia',
'Panamá',
'Costa Rica',
'Cuba',
'República Dominicana',
'Guatemala',
'Honduras',
'El Salvador',
'Nicaragua',
'Puerto Rico',
'México',
'Estados Unidos',
'Canadá',
'Guayana',
'Surinam',
'Guyana Francesa',
];
document.getElementById('search').addEventListener('input', () => {
const query = document.getElementById('search').value.toLowerCase();
const resultsList = document.getElementById('resultsList');
resultsList.innerHTML = '';
const filteredCountries = countries.filter(country =>
country.toLowerCase().includes(query)
);
filteredCountries.forEach(country => {
const li = document.createElement('li');
li.textContent = country;
resultsList.appendChild(li);
});
});

View File

@@ -8,7 +8,11 @@
</head> </head>
<body> <body>
<h1>Ejercicio 5</h1> <h1>Ejercicio 5</h1>
<div id="results">
<label for="search">Buscar:</label>
<input type="text" id="search" name="search">
<ul id="resultsList"></ul>
</div>
<script src="ejercicio5.js"></script> <script src="ejercicio5.js"></script>
</body> </body>
</html> </html>

View File

@@ -1 +1,43 @@
// Agregar aquí el código javascript // Agregar aquí el código javascript
const employees = [
{ name: "Ana", sector: "Desarrollo", salary: 150000 },
{ name: "Luis", sector: "Diseño", salary: 120000 },
{ name: "Marta", sector: "Desarrollo", salary: 160000 },
{ name: "Carlos", sector: "RRHH", salary: 110000 },
{ name: "Julia", sector: "Diseño", salary: 130000 }
];
const tableContainer = document.getElementById('tableEmployees');
const table = document.createElement('table');
const headerRow = document.createElement('tr');
['Nombre', 'Sector', 'Salario'].forEach(headerText => {
const th = document.createElement('th');
th.textContent = headerText;
headerRow.appendChild(th);
});
table.appendChild(headerRow);
tableContainer.appendChild(table);
employees.forEach(employee => {
const row = document.createElement('tr');
['name', 'sector', 'salary'].forEach(key => {
const td = document.createElement('td');
td.textContent = employee[key];
row.appendChild(td);
});
table.appendChild(row);
});
table.appendChild(document.createElement('tr')); // Fila vacía para separación
const averageSalary = employees.reduce((sum, emp) => sum + emp.salary, 0) / employees.length;
const averageRow = document.createElement('tr');
const averageLabelCell = document.createElement('td');
averageLabelCell.textContent = 'Salario Promedio';
averageRow.appendChild(averageLabelCell);
const averageValueCell = document.createElement('td');
averageValueCell.textContent = averageSalary;
averageRow.appendChild(averageValueCell);
table.appendChild(averageRow);

View File

@@ -8,7 +8,9 @@
</head> </head>
<body> <body>
<h1>Ejercicio 6</h1> <h1>Ejercicio 6</h1>
<div id="tableEmployees">
</div>
<script src="ejercicio6.js"></script> <script src="ejercicio6.js"></script>
</body> </body>
</html> </html>

View File

@@ -1 +1,24 @@
// Agregar aquí el código javascript // Agregar aquí el código javascript
const userForm = document.getElementById('userForm');
userForm.addEventListener('submit', (event) => {
event.preventDefault();
const username = document.getElementById('username').value.trim();
const age = parseInt(document.getElementById('age').value);
const password = document.getElementById('password').value;
if (username === '') {
alert('El nombre de usuario no puede estar vacío.');
return;
}
if (isNaN(age) || age < 0 || age > 100) {
alert('La edad debe ser un número válido entre 0 y 100.');
return;
}
if (password.length < 8) {
alert('La contraseña debe tener al menos 8 caracteres.');
return;
}
alert('Formulario enviado correctamente.');
userForm.reset();
});

View File

@@ -8,7 +8,15 @@
</head> </head>
<body> <body>
<h1>Ejercicio 7</h1> <h1>Ejercicio 7</h1>
<form id="userForm">
<label for="username">Nombre de usuario:</label>
<input type="text" id="username" name="username" required>
<label for="age">Edad:</label>
<input type="number" id="age" name="age" required>
<label for="password">Contraseña:</label>
<input type="password" id="password" name="password" required>
<button type="submit">Enviar</button>
</form>
<script src="ejercicio7.js"></script> <script src="ejercicio7.js"></script>
</body> </body>
</html> </html>

View File

@@ -1 +1,68 @@
// Agregar aquí el código javascript // Agregar aquí el código javascript
const products = [
{ name: "Teclado", price: 8500 },
{ name: "Mouse", price: 4200 },
{ name: "Monitor", price: 62000 },
{ name: "Auriculares", price: 11000 },
{ name: "Webcam", price: 15500 }
];
const productList = document.getElementById('productList');
const checkout = document.getElementById('checkout');
products.forEach(product => {
const productDiv = document.createElement('div');
productDiv.textContent = `${product.name} - $${product.price} `;
const buyButton = document.createElement('button');
buyButton.textContent = 'Comprar';
productDiv.appendChild(buyButton);
productList.appendChild(productDiv);
});
const cart = new Map();
const renderCart = () => {
checkout.innerHTML = '';
if (cart.size === 0) {
checkout.innerHTML = '<p>Carrito vacío</p>';
return;
}
let totalPrice = 0;
cart.forEach((quantity, product) => {
const lineTotal = product.price * quantity;
totalPrice += lineTotal;
const itemRow = document.createElement('div');
itemRow.innerHTML = `
<div>${product.name} -------- x${quantity}</div>
<div>$${lineTotal.toLocaleString()}</div>
`;
checkout.appendChild(itemRow);
});
const totalRow = document.createElement('div');
totalRow.innerHTML = `<strong>Total: ------------- $${totalPrice.toLocaleString()}</strong>`;
checkout.appendChild(totalRow);
};
productList.addEventListener('click', (event) => {
if (event.target.tagName === 'BUTTON') {
const productDiv = event.target.parentElement;
const productName = productDiv.textContent.split(' - ')[0];
const product = products.find(p => p.name === productName);
if (!product) {
return;
}
const currentQty = cart.get(product) || 0;
cart.set(product, currentQty + 1);
renderCart();
}
});
renderCart();

View File

@@ -8,7 +8,12 @@
</head> </head>
<body> <body>
<h1>Ejercicio 8</h1> <h1>Ejercicio 8</h1>
<div id="productList">
<!-- Acá se mostrarán los productos -->
</div>
<div id="checkout">
<!-- Acá se mostrará el precio total -->
</div>
<script src="ejercicio8.js"></script> <script src="ejercicio8.js"></script>
</body> </body>
</html> </html>

View File

@@ -1,133 +1,80 @@
const preguntas = [ // Agregar aquí el código javascript
const questions = [
{ {
pregunta: "¿Cuál es la diferencia entre let y const?", question: "¿Cuál es la capital de Francia?",
opciones: [ options: ["Londres", "Berlín", "París", "Roma"],
"No hay diferencia, son equivalentes", correctAnswer: 2
"let permite reasignar el valor, const no",
"Depende del tipo de datos",
"let solo funciona dentro de funciones"
],
correcta: 1
}, },
{ {
pregunta: "¿Qué retorna querySelector si no encuentra ningún elemento?", question: "¿Cuál es el río más largo del mundo?",
opciones: ["undefined", "false", "null", "0"], options: ["Nilo", "Amazonas", "Yangtsé", "Misisipi"],
correcta: 2 correctAnswer: 1
}, },
{ {
pregunta: "¿Qué hace el método filter?", question: "¿Quién escribió 'Cien años de soledad'?",
opciones: [ options: ["Gabriel García Márquez", "Mario Vargas Llosa", "Isabel Allende", "Jorge Luis Borges"],
"Modifica los elementos del array original", correctAnswer: 0
"Retorna el primer elemento que cumple la condición",
"Retorna un nuevo array con los elementos que cumplen la condición",
"Elimina elementos duplicados del array"
],
correcta: 2
}, },
{ {
pregunta: "¿Cuál es el operador de igualdad estricta en JavaScript?", question: "¿Cuál es el planeta más grande del sistema solar?",
opciones: ["=", "==", "===", "!="], options: ["Júpiter", "Saturno", "Urano", "Neptuno"],
correcta: 2 correctAnswer: 0
}, },
{ {
pregunta: "¿Para qué sirve event.preventDefault()?", question: "¿En qué año se descubrió América?",
opciones: [ options: ["1492", "1500", "1485", "1510"],
"Detiene la propagación del evento hacia elementos padre", correctAnswer: 0
"Evita el comportamiento por defecto del navegador",
"Elimina el event listener del elemento",
"Pausa la ejecución del código hasta que el evento termine"
],
correcta: 1
} }
]; ];
let indiceActual = 0; let currentQuestionIndex = 0;
let puntaje = 0; let score = 0;
const pantalla = document.querySelector("#pantalla-quiz"); const questionElement = document.getElementById('question');
const resultadoEl = document.querySelector("#resultado"); const optionsElement = document.getElementById('options');
const preguntaEl = document.querySelector("#pregunta"); const resultElement = document.getElementById('result');
const opcionesEl = document.querySelector("#opciones");
const feedbackEl = document.querySelector("#feedback");
const btnSiguiente = document.querySelector("#siguiente");
const progresoEl = document.querySelector("#progreso");
const progressFill = document.querySelector("#progress-fill");
const puntajeNumEl = document.querySelector("#puntaje-num");
const resultadoMsg = document.querySelector("#resultado-msg");
const btnReiniciar = document.querySelector("#reiniciar");
function mensajeFinal(p, total) { const loadQuestion = () => {
if (p === total) return "¡Perfecto! Todo bien."; const currentQuestion = questions[currentQuestionIndex];
if (p >= total * 0.8) return "¡Muy bien!"; questionElement.textContent = currentQuestion.question;
if (p >= total * 0.6) return "Bien, pero hay margen para mejorar."; optionsElement.innerHTML = '';
return "Vale la pena repasar los temas."; currentQuestion.options.forEach((option, index) => {
} const li = document.createElement('li');
const button = document.createElement('button');
function mostrarPregunta() { button.textContent = option;
const actual = preguntas[indiceActual]; li.appendChild(button);
button.addEventListener('click', () => checkAnswer(index));
// Actualizamos el encabezado y la barra de progreso. optionsElement.appendChild(li);
progresoEl.textContent = `${indiceActual + 1} / ${preguntas.length}`;
progressFill.style.width = `${(indiceActual / preguntas.length) * 100}%`;
preguntaEl.textContent = actual.pregunta;
opcionesEl.innerHTML = "";
feedbackEl.textContent = "";
btnSiguiente.style.display = "none";
for (let i = 0; i < actual.opciones.length; i++) {
const boton = document.createElement("button");
boton.className = "opcion";
boton.textContent = actual.opciones[i];
boton.addEventListener("click", () => responder(i));
opcionesEl.appendChild(boton);
}
}
function responder(indiceRespuesta) {
const actual = preguntas[indiceActual];
const botones = opcionesEl.querySelectorAll(".opcion");
// Deshabilitamos todos los botones para que no se pueda responder dos veces.
for (const boton of botones) {
boton.disabled = true;
}
if (indiceRespuesta === actual.correcta) {
botones[indiceRespuesta].classList.add("correcta");
feedbackEl.textContent = "¡Correcto!";
puntaje++;
} else {
botones[indiceRespuesta].classList.add("incorrecta");
botones[actual.correcta].classList.add("correcta");
feedbackEl.textContent = `Incorrecto. La correcta era: "${actual.opciones[actual.correcta]}"`;
}
btnSiguiente.style.display = "inline-block";
}
btnSiguiente.addEventListener("click", () => {
indiceActual++;
if (indiceActual < preguntas.length) {
mostrarPregunta();
} else {
// Actualizamos la barra al 100% antes de mostrar el resultado.
progressFill.style.width = "100%";
pantalla.style.display = "none";
resultadoEl.style.display = "block";
puntajeNumEl.textContent = `${puntaje} / ${preguntas.length}`;
resultadoMsg.textContent = mensajeFinal(puntaje, preguntas.length);
}
}); });
};
btnReiniciar.addEventListener("click", () => { const checkAnswer = (selectedIndex) => {
indiceActual = 0; const currentQuestion = questions[currentQuestionIndex];
puntaje = 0; if (selectedIndex === currentQuestion.correctAnswer) {
resultadoEl.style.display = "none"; resultElement.textContent = "¡Correcto!";
pantalla.style.display = "block"; score++;
mostrarPregunta(); currentQuestionIndex++;
}); if (currentQuestionIndex < questions.length) {
setTimeout(() => {
resultElement.textContent = '';
loadQuestion();
}, 1000);
} else {
resultElement.textContent = `¡Juego terminado! Tu puntuación es ${score}/${questions.length}.`;
}
} else {
resultElement.textContent = "Incorrecto. La respuesta correcta es: " + currentQuestion.options[currentQuestion.correctAnswer];
currentQuestionIndex++;
if (currentQuestionIndex < questions.length) {
setTimeout(() => {
resultElement.textContent = '';
loadQuestion();
}, 2000);
} else {
resultElement.textContent = `¡Juego terminado! Tu puntuación es ${score}/${questions.length}.`;
}
}
};
mostrarPregunta(); loadQuestion();

View File

@@ -1,168 +1,2 @@
/* Hoja de estilo realizada con IA */ /* Agregar el código CSS necesario para el ejercicio */
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: system-ui, sans-serif;
background: #f5f4f0;
color: #1a1a1a;
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 2rem;
}
.card {
background: #fff;
border: 0.5px solid #ddd;
border-radius: 16px;
padding: 2rem;
width: 100%;
max-width: 520px;
}
/* ── Encabezado ── */
.quiz-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 1.5rem;
}
.quiz-title {
font-size: 0.7rem;
font-weight: 500;
color: #888;
text-transform: uppercase;
letter-spacing: 0.06em;
}
.quiz-progress {
font-size: 0.75rem;
color: #aaa;
}
/* ── Barra de progreso ── */
.progress-bar {
height: 4px;
background: #eee;
border-radius: 2px;
margin-bottom: 2rem;
overflow: hidden;
}
.progress-fill {
height: 100%;
background: #1a1a1a;
border-radius: 2px;
transition: width 0.3s ease;
}
/* ── Pregunta ── */
#pregunta {
font-size: 1.05rem;
font-weight: 500;
line-height: 1.5;
margin-bottom: 1.5rem;
min-height: 3rem;
}
/* ── Opciones ── */
#opciones {
display: flex;
flex-direction: column;
gap: 8px;
margin-bottom: 1.5rem;
}
.opcion {
width: 100%;
text-align: left;
padding: 12px 16px;
background: #f5f4f0;
border: 0.5px solid #ddd;
border-radius: 8px;
font-size: 0.875rem;
color: #1a1a1a;
cursor: pointer;
transition: background 0.15s, border-color 0.15s;
}
.opcion:hover:not(:disabled) {
background: #edecea;
border-color: #bbb;
}
.opcion:disabled { cursor: default; }
.opcion.correcta {
background: #eaf3de;
border-color: #639922;
color: #3b6d11;
}
.opcion.incorrecta {
background: #fcebeb;
border-color: #e24b4a;
color: #a32d2d;
}
/* ── Feedback ── */
#feedback {
font-size: 0.8rem;
min-height: 1.2rem;
color: #555;
margin-bottom: 1.25rem;
}
/* ── Botones de acción ── */
.btn {
padding: 10px 20px;
font-size: 0.875rem;
font-weight: 500;
border-radius: 8px;
border: 0.5px solid #ccc;
background: #1a1a1a;
color: #fff;
cursor: pointer;
transition: opacity 0.15s;
}
.btn:hover { opacity: 0.85; }
.btn-secondary {
background: transparent;
color: #1a1a1a;
}
/* ── Pantalla de resultado ── */
#resultado {
text-align: center;
padding: 1rem 0;
}
.resultado-score {
font-size: 3rem;
font-weight: 500;
line-height: 1;
margin-bottom: 0.5rem;
}
.resultado-label {
font-size: 0.875rem;
color: #888;
margin-bottom: 0.5rem;
}
.resultado-msg {
font-size: 1rem;
font-weight: 500;
margin-bottom: 2rem;
}

View File

@@ -7,37 +7,13 @@
<link rel="stylesheet" href="estilo.css"> <link rel="stylesheet" href="estilo.css">
</head> </head>
<body> <body>
<h1>Ejercicio 9</h1>
<div class="card"> <div id="quizGame">
<p id="instructions">Responde a la pregunta correcta</p>
<div id="pantalla-quiz"> <p id="question"></p>
<div class="quiz-header"> <ul id="options"></ul>
<span class="quiz-title">Ejercicio 9 - Quiz de JavaScript</span> <p id="result"></p>
<span class="quiz-progress" id="progreso">1 / 5</span>
</div> </div>
<div class="progress-bar">
<div class="progress-fill" id="progress-fill" style="width: 0%"></div>
</div>
<p id="pregunta"></p>
<div id="opciones"></div>
<p id="feedback"></p>
<button class="btn" id="siguiente" style="display:none">Siguiente →</button>
</div>
<div id="resultado" style="display:none">
<p class="resultado-score" id="puntaje-num"></p>
<p class="resultado-label">respuestas correctas</p>
<p class="resultado-msg" id="resultado-msg"></p>
<button class="btn btn-secondary" id="reiniciar">Reiniciar quiz</button>
</div>
</div>
<script src="ejercicio9.js"></script> <script src="ejercicio9.js"></script>
</body> </body>
</html> </html>