Semana 3 Introduccin A JavaScript y Jquery
Semana 3 Introduccin A JavaScript y Jquery
JavaScript y jQuery
Created @February 1, 2025 10:45 AM
Tags
Qué es JavaScript?
JavaScript es un lenguaje de programación interpretado, de alto nivel y orientado
a objetos basado en prototipos. Se utiliza principalmente para el desarrollo web
del lado del cliente, aunque también es empleado en el lado del servidor mediante
tecnologías como Node.js.
Es uno de los tres lenguajes fundamentales del desarrollo web:
Operadores en JavaScript
Operadores Aritméticos
+ , - , * , / , % , ++ , --
let suma = 10 + 5; // 15
let residuo = 10 % 3; // 1
let residuoPar = 10 % 2; // 0
Operadores de Comparación
== , === , != , !== , < , > , <= , >=
Operadores Lógicos
&& (AND), || (OR), ! (NOT)
Estructuras de Control
1. Condicionales:
2. Switch 🚫:
let dia = 3;
switch (dia) {
case 1: console.log("Lunes"); break;
case 2: console.log("Martes"); break;
case 3: console.log("Miércoles"); break;
default: console.log("Día no válido");
}
for
while
do-while
foreach
numeros.forEach(function(numero) {
console.log(numero * 2); // Imprime el doble de cada número
});
frutas.forEach(function(fruta, indice) {
console.log(`La fruta en el índice ${indice} es: ${fruta}`);
});
function saludar(nombre) {
return "Hola, " + nombre + "!";
}
console.log(saludar("Yeison"));
Eventos en el DOM
Los eventos permiten la interacción del usuario con la página.
document.getElementById("btn").addEventListener("click", function() {
alert("¡Hiciste clic en el botón!");
});
El
DOM (Document Object Model) es una representación estructurada del
documento HTML que permite a JavaScript acceder y manipular los elementos de
la página. A través del DOM podemos modificar contenido, cambiar estilos,
agregar o eliminar elementos, y responder a eventos del usuario.
Técnicamente el DOM es una API Web que permite a los desarrolladores usar la
lógica de programación para realizar cambios en el código
Para tener acceso a los elementos de HTML que se quieren manipular, necesitas
hacer que JavaScript sea consciente de la existencia de dichos elementos. A esto
nos referimos generalmente como "selección" de elementos – básicamente es
enlazarlos.
Selección de elementos
document.getElementById("miBoton").addEventListener("click", function() {
alert("¡Botón clickeado!");
});
document.getElementById("miFormulario").addEventListener("submit", function(
event.preventDefault(); // Evita que el formulario se envíe
alert("Formulario enviado correctamente");
});
Ventajas de jQuery
✅ Sintaxis simple y fácil de aprender.
✅ Reduce la cantidad de código JavaScript necesario.
✅ Compatible con múltiples navegadores.
✅ Facilita la manipulación del DOM y eventos.
✅ Integra efectos y animaciones avanzadas.
Selectores en jQuery:
Los selectores en jQuery se basan en la sintaxis de CSS y se invocan mediante
$() .
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
Descarga Local
$(selector).acción();
<p id="miParrafo"></p>
$(document).ready(function(){
$("#miParrafo").text("Nuevo texto con jQuery");
});
$(document).ready(function(){
$("p").css("color", "blue");
});
$("#miInput").val("Nuevo valor");
$("#miInput").val(); // recoge el valor que tiene #input
$("a").attr("href", "https://google.com");
$('form').submit(function(event) {
Se activa cuando se envía un
submit event.preventDefault(); alert('Formulario
formulario. enviado'); });
$('#box').mouseover(function() {
Se activa cuando el puntero del
mouseover $(this).css('background-color', 'yellow');
mouse entra en un elemento. });
$('#box').mouseout(function() {
Se activa cuando el puntero del
mouseout $(this).css('background-color', 'white');
mouse sale de un elemento. });
Efectos y AJAX
1️⃣ Efectos y Animaciones
Método Descripción Ejemplo
.hide() Oculta un elemento $("#caja").hide();
1. .hide :
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hide Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
#caja {
width: 200px;
height: 100px;
<script>
$(document).ready(function() {
$('#btnHide').click(function() {
$('#caja').hide(); // Oculta la caja
});
});
</script>
</body>
</html>
2. .show()
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Show Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
#caja {
width: 200px;
height: 100px;
background-color: lightgreen;
text-align: center;
<script>
$(document).ready(function() {
$('#btnShow').click(function() {
$('#caja').show(); // Muestra la caja
});
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FadeIn Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
#caja {
width: 200px;
height: 100px;
background-color: lightcoral;
text-align: center;
line-height: 100px;
<script>
$(document).ready(function() {
$('#btnFadeIn').click(function() {
$('#caja').fadeIn(1000); // Aparece con un efecto de desvanecimien
});
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FadeOut Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
#caja {
width: 200px;
height: 100px;
background-color: lightseagreen;
text-align: center;
line-height: 100px;
}
<script>
$(document).ready(function() {
$('#btnFadeOut').click(function() {
$('#caja').fadeOut(1000); // Desvanece la caja en 1 segundo
});
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SlideDown Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
#caja {
width: 200px;
height: 100px;
background-color: lightgoldenrodyellow;
text-align: center;
line-height: 100px;
display: none; /* Inicialmente oculto */
}
</style>
<script>
$(document).ready(function() {
$('#btnSlideDown').click(function() {
$('#caja').slideDown(1000); // Muestra la caja con un efecto de des
});
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SlideUp Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
#caja {
width: 200px;
height: 100px;
background-color: lightpink;
text-align: center;
line-height: 100px;
}
</style>
</head>
<body>
<script>
$(document).ready(function() {
$('#btnSlideUp').click(function() {
$('#caja').slideUp(1000); // Oculta la caja con un efecto de deslizam
});
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Toggle Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
#caja {
width: 200px;
height: 100px;
background-color: lightskyblue;
text-align: center;
line-height: 100px;
}
</style>
</head>
<body>
<div id="caja">Caja Visible</div>
<button id="btnToggle">Alternar</button>
Ajax
Ventajas de AJAX
Desventajas de AJAX
1. SEO limitado : Los motores de búsqueda pueden tener dificultades para
indexar contenido cargado dinámicamente.
Cargar
.load() contenido $("#div").load("archivo.html")
AJAX
Obtener datos
$.get() $.get("api.php", function(d){ console.log(d); });
AJAX
Ejemplo:
<script>
$(document).ready(function() {
$('#btnCargarUsuarios').click(function() {
$.ajax({
url: 'https://jsonplaceholder.typicode.com/users', // URL de la API
method: 'GET',
dataType: 'json',
success: function(data) {
let lista = '';
data.forEach(usuario => {
lista += `<li>${usuario.name} (${usuario.email})</li>`;
});
$('#listaUsuarios').html(lista); // Mostrar la lista en el DOM
},
error: function() {
alert('Error al cargar los usuarios.');
}
});
});
});
</script>
Proyecto JQUERY
Ejercicios Integradores (HTML, CSS y JavaScript)
Ejercicio 1: Formulario Validado con jQuery
Crea un formulario de contacto con validación en tiempo real. Debe verificar que
los campos no estén vacíos y que el correo tenga un formato válido.
<!DOCTYPE html>
<html>
<head>
<title>Formulario Validado</title>
<style>
.error {
color: red;
}
</style>
</head>
<body>
<form id="formulario">
<label for="email">Correo Electrónico:</label>
<input type="email" id="email" name="email">
<button type="submit">Enviar</button>
</form>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$("#formulario").submit(function(event) {
let email = $("#email").val();
$(document).ready(function() {
$("#formulario").submit(function(event) {
let email = $("#email").val();
let regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
<!DOCTYPE html>
<html>
<head>
<title>Menú Desplegable</title>
<style>
#menu {
$(document).ready(function() {
$("#boton-menu").click(function() {
$("#menu").slideToggle();
});
});
$(document).ready(function() {
let actual = 0;
$("#siguiente").click(function() {
$(imagenes[actual]).hide();
actual = (actual + 1) % imagenes.length;
$(imagenes[actual]).show();
});
$("#anterior").click(function() {
$(imagenes[actual]).hide();
actual = (actual - 1 + imagenes.length) % imagenes.length;
$(imagenes[actual]).show();
});
});
<!DOCTYPE html>
<html>
<head>
<title>Lista de Tareas</title>
</head>
<body>
<input type="text" id="tarea">
<button id="agregar">Agregar</button>
<ul id="lista"></ul>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$("#agregar").click(function() {
let tarea = $("#tarea").val();
if(tarea) {
$("#lista").append("<li>" + tarea + " <button class='eliminar'>X</but
$(document).ready(function() {
$("#agregar").click(function() {
let tarea = $("#tarea").val();
if(tarea) {
$("#lista").append("<li>" + tarea + " <button class='eliminar'>X</button>
$("#tarea").val("");
}
});
Proyecto Semana 3:
Interfaz Dinámica con jQuery:
Agregar al ejercicio del portafolio dinamismo, como un formulario de contacto,
entre otras.