├── .DS_Store ├── .vscode └── settings.json ├── After 1 (Funciones y objetos) ├── ejemploEntregable.js ├── index.html └── index.js ├── After 2 (HOF) ├── index.html └── index.js ├── After 3 (Storage y JSON) ├── ejemplo_base │ ├── index.html │ └── index.js ├── index.html └── index.js ├── After 4 (AJAX) ├── .vscode │ └── settings.json ├── ejemplo_base │ ├── index.html │ ├── index.js │ ├── productos.json │ └── style.css └── ejemplo_completo │ ├── index.html │ ├── index.js │ ├── productos.json │ └── style.css ├── Clase 1 (Sintaxis) ├── index.html └── index.js ├── Clase 10 (Storage y JSON) ├── .DS_Store ├── ejemplo_base │ ├── index.html │ └── index.js ├── index.html └── index.js ├── Clase 12 (Operadores avanzados) ├── index.html └── index.js ├── Clase 13 (Librerías) ├── ejemplo_base │ ├── index.html │ └── index.js ├── ejemplo_completo │ ├── index.html │ ├── index.js │ └── style.css ├── index.html └── index.js ├── Clase 14 (Async y promesas) ├── index.html └── index.js ├── Clase 15 (AJAX y Fetch) ├── ejemplo_base │ ├── index.html │ ├── index.js │ └── style.css └── ejemplo_completo │ ├── index.html │ ├── index.js │ ├── productos.json │ └── style.css ├── Clase 16 (Frameworks y nodejs) ├── ejemplo_node │ ├── .gitignore │ ├── app.js │ ├── controllers │ │ └── products.js │ ├── index.js │ ├── models │ │ └── Product.js │ ├── package-lock.json │ ├── package.json │ └── routes │ │ └── products.js └── ejemplo_react │ ├── .gitignore │ ├── README.md │ ├── package-lock.json │ ├── package.json │ ├── public │ ├── favicon.ico │ ├── index.html │ ├── logo192.png │ ├── logo512.png │ ├── manifest.json │ └── robots.txt │ └── src │ ├── App.js │ └── index.js ├── Clase 2 (Control de flujos) ├── .DS_Store ├── index.html └── index.js ├── Clase 3 (Cilclos e iteraciones) ├── index.html └── index.js ├── Clase 4 (Funciones) ├── index.html └── index.js ├── Clase 5 (Objetos) ├── index.html └── index.js ├── Clase 6 (Arrays) ├── index.html └── index.js ├── Clase 7 (HOF) ├── index.html └── index.js ├── Clase 8 (DOM) ├── index.html ├── index.js └── styles.css └── Clase 9 (Eventos) ├── index.html └── index.js /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JesusBrito/comision-34015-javascript/63d372d3a93333c1e79978d73ba60ca7f9399bb9/.DS_Store -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "liveServer.settings.port": 5502 3 | } -------------------------------------------------------------------------------- /After 1 (Funciones y objetos)/ejemploEntregable.js: -------------------------------------------------------------------------------- 1 | function suma(numeroUno, numeroDos) { 2 | let resultado = numeroUno + numeroDos; 3 | return resultado; 4 | } 5 | 6 | function resta(numeroUno, numeroDos) { 7 | let resultado = numeroUno - numeroDos; 8 | return resultado; 9 | } 10 | 11 | function multiplicacion(numeroUno, numeroDos) { 12 | let resultado = numeroUno * numeroDos; 13 | return resultado; 14 | } 15 | 16 | function division(numeroUno, numeroDos) { 17 | let resultado = numeroUno / numeroDos; 18 | return resultado; 19 | } 20 | 21 | function mostrarResultado(resultado) { 22 | alert("El resultado de la operación es: " + resultado); 23 | } 24 | 25 | function mostrarMenu() { 26 | let opcion = prompt( 27 | "Bienvenido, seleccione una opción (ESC para salir)\n1. Sumar\n2. Restar\n3. Multiplicar\n4. Dividir" 28 | ); 29 | return opcion; 30 | } 31 | 32 | function calculadora() { 33 | let opcionSeleccionada = mostrarMenu(); 34 | while (opcionSeleccionada !== "ESC") { 35 | if (opcionSeleccionada !== "") { 36 | opcionSeleccionada = parseInt(opcionSeleccionada); 37 | 38 | //isNaN nos sirve para saber si el contenido de una variable es NaN 39 | if (!isNaN(opcionSeleccionada)) { 40 | let numeroUno = parseFloat(prompt("Ingrese el primer numero")); 41 | let numeroDos = parseFloat(prompt("Ingrese el segundo numero")); 42 | switch (opcionSeleccionada) { 43 | case 1: 44 | let resultadoSuma = suma(numeroUno, numeroDos); 45 | mostrarResultado(resultadoSuma); 46 | break; 47 | 48 | case 2: 49 | let resultadoResta = resta(numeroUno, numeroDos); 50 | mostrarResultado(resultadoResta); 51 | break; 52 | 53 | case 3: 54 | let resultadoMultiplicacion = multiplicacion(numeroUno, numeroDos); 55 | mostrarResultado(resultadoMultiplicacion); 56 | break; 57 | 58 | case 4: 59 | let resultadoDivision = division(numeroUno, numeroDos); 60 | mostrarResultado(resultadoDivision); 61 | break; 62 | 63 | default: 64 | alert("Opcion Incorrecta"); 65 | break; 66 | } 67 | } else { 68 | alert("Ingresó una letra"); 69 | } 70 | } else { 71 | alert("Seleccione la opción"); 72 | } 73 | opcionSeleccionada = mostrarMenu(); 74 | } 75 | } 76 | 77 | calculadora(); -------------------------------------------------------------------------------- /After 1 (Funciones y objetos)/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /After 1 (Funciones y objetos)/index.js: -------------------------------------------------------------------------------- 1 | //========= CONCEPTO THIS ========= 2 | // console.log(this); 3 | 4 | // var name = "name window"; 5 | 6 | // let objetoPrueba = { 7 | // name: "name object", 8 | // getName: obtenerNombre, 9 | // }; 10 | 11 | // function obtenerNombre() { 12 | // console.log(this); 13 | // console.log("Mi nombre es: " + this.name); 14 | // } 15 | 16 | // obtenerNombre(); 17 | // objetoPrueba.getName(); 18 | 19 | //========= EJEMPLO AVANZADO ========= 20 | let miProducto; 21 | 22 | class Producto { 23 | constructor(nombre, precioCompra, precioVenta, cantidad) { 24 | this.nombre = nombre; 25 | this.precioVenta = precioVenta; 26 | this.precioCompra = precioCompra; 27 | this.cantidad = cantidad; 28 | } 29 | 30 | vender() { 31 | console.log(this); 32 | if (this.cantidad > 0) { 33 | this.disminuirStock(1); 34 | } else { 35 | alert("Ya no hay disponibilidad"); 36 | } 37 | } 38 | aumentarPrecio = (precio) => (this.precioVenta += precio); 39 | disminuirPrecio = (precio) => (this.precioVenta -= precio); 40 | aumentarStock = (cantidad) => (this.cantidad += cantidad); 41 | disminuirStock = (cantidad) => (this.cantidad -= cantidad); 42 | } 43 | 44 | function obtenerDatosDeProducto() { 45 | let nombre = prompt("Ingresa el nombre del producto"); 46 | let precio = parseFloat(prompt("Ingresa el precio de venta del producto")); 47 | let precioCompra = parseFloat( 48 | prompt("Ingresa el precio de compra del producto") 49 | ); 50 | let cantidad = parseInt(prompt("Ingresa la cantidad de productos")); 51 | 52 | const objetoProducto = new Producto(nombre, precioCompra, precio, cantidad); 53 | return objetoProducto; 54 | } 55 | 56 | function mostrarMenu() { 57 | const OPCION = prompt( 58 | "Bienvenido, seleccione una opción (ESC para salir)\n1. Agregar datos del producto\n2. Aumentar precio\n3. Disminuir precio\n4. Aumentar stock\n5. Disminuir stock\n6. Vender\n7. Mostrar información del producto" 59 | ); 60 | return OPCION; 61 | } 62 | 63 | function convertirObjetoEnTexto(objeto) { 64 | let texto = ""; 65 | for (const clave in objeto) { 66 | if (typeof objeto[clave] !== "function") 67 | texto += clave + " : " + objeto[clave] + "\n"; 68 | } 69 | return texto; 70 | } 71 | 72 | function procesarInventario() { 73 | let opcionSeleccionada = mostrarMenu(); 74 | while (opcionSeleccionada?.toLowerCase() != "esc") { 75 | if (opcionSeleccionada != "") { 76 | opcionSeleccionada = parseInt(opcionSeleccionada); 77 | if (!isNaN(opcionSeleccionada)) { 78 | switch (opcionSeleccionada) { 79 | case 1: 80 | miProducto = obtenerDatosDeProducto(); 81 | break; 82 | case 2: 83 | const PRECIO_A_AUMENTAR = parseFloat( 84 | prompt("Ingrese en cuanto aumenta el precio del producto") 85 | ); 86 | miProducto.aumentarPrecio(PRECIO_A_AUMENTAR); 87 | break; 88 | 89 | case 3: 90 | const PRECIO_A_DISMINUIR = parseFloat( 91 | prompt("Ingrese en cuanto disminuye el precio del producto") 92 | ); 93 | miProducto.disminuirPrecio(PRECIO_A_DISMINUIR); 94 | break; 95 | 96 | case 4: 97 | const PRODUCTOS_A_AUMENTAR = parseInt( 98 | prompt("Ingrese la cantidad de productos a aumentar") 99 | ); 100 | miProducto.aumentarStock(PRODUCTOS_A_AUMENTAR); 101 | break; 102 | 103 | case 5: 104 | const PRODUCTOS_A_DISMINUIR = parseInt( 105 | prompt("Ingrese la cantidad de productos a disminuir") 106 | ); 107 | miProducto.disminuirStock(PRODUCTOS_A_DISMINUIR); 108 | break; 109 | 110 | case 6: 111 | miProducto.vender(); 112 | break; 113 | 114 | case 7: 115 | const OBJETO_TEXTO = convertirObjetoEnTexto(miProducto); 116 | alert(OBJETO_TEXTO); 117 | break; 118 | 119 | default: 120 | alert("Opcion Incorrecta"); 121 | break; 122 | } 123 | } else { 124 | alert("Ingresó una letra"); 125 | } 126 | } else { 127 | alert("Seleccione la opción"); 128 | } 129 | opcionSeleccionada = mostrarMenu(); 130 | } 131 | } 132 | 133 | function main() { 134 | miProducto = obtenerDatosDeProducto(); 135 | procesarInventario(); 136 | } 137 | 138 | main(); 139 | -------------------------------------------------------------------------------- /After 2 (HOF)/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /After 2 (HOF)/index.js: -------------------------------------------------------------------------------- 1 | //================ FIND EN ARREGLO DE OBJETOS ================ 2 | 3 | // let arrayProductos = [ 4 | // { nombre: "Laptop", precio: 1000, cantidad: 3 }, 5 | // { nombre: "PC", precio: 800, cantidad: 2 }, 6 | // { nombre: "iPhone", precio: 1200, cantidad: 5 }, 7 | // ]; 8 | 9 | // let elementoEncontrado = arrayProductos.find( 10 | // (elemento) => elemento.nombre === "Laptop" 11 | // ); 12 | 13 | // console.log(elementoEncontrado); 14 | 15 | //================ OBTENER VALORES DE LA FECHA ================ 16 | 17 | // const hoy = new Date() 18 | 19 | // console.log(hoy.getFullYear()) 20 | // console.log(hoy.getMonth()) 21 | // console.log(hoy.getDay()) 22 | 23 | //================ EJEMPLO DATE DIFERENCIAS FECHAS ================ 24 | 25 | const fechaActual = new Date(); 26 | const milisegundosPorDia = 86400000; 27 | 28 | let dia = parseInt(prompt("Ingresa tu día de nacimiento")); 29 | let mes = parseInt(prompt("Ingresa tu mes de nacimiento")); 30 | let anio = parseInt(prompt("Ingresa tu año de nacimiento")); 31 | 32 | const cumpleanios = new Date(anio, mes - 1, dia); 33 | const diferenciaDias = (fechaActual - cumpleanios) / milisegundosPorDia; 34 | const diferenciaAnios = diferenciaDias / 365; 35 | 36 | alert(`Naciste hace ${diferenciaAnios} años`); 37 | alert(`Naciste hace ${Math.floor(diferenciaAnios)} años`); 38 | alert(`Naciste hace ${Math.ceil(diferenciaAnios)} años`); -------------------------------------------------------------------------------- /After 3 (Storage y JSON)/ejemplo_base/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 14 | 15 | 16 |
17 |
18 |
19 | 22 |
23 |
24 | 27 |
28 |

Identificate

29 |
30 |
31 |
32 |
33 | 34 | 40 |
41 |
42 |
43 | 46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |

Ejemplo formulario

59 |
60 |
61 | 62 | 63 |
64 |
65 | 66 | 72 |
73 | 74 |
75 | 76 | 82 |
83 | 84 |
85 | 86 | 92 |
93 | 94 |
95 | 96 | 102 |
103 | 104 |
105 | 106 |
107 |
108 |
109 |
110 |
111 | 116 | 117 | 118 | 119 | -------------------------------------------------------------------------------- /After 3 (Storage y JSON)/ejemplo_base/index.js: -------------------------------------------------------------------------------- 1 | //================ SESSION STORAGE ================ 2 | //Se utiliza para almacenar información en el navegador, 3 | // esta información se elimina si se cierra el navegador 4 | // o se cierra la pestaña 5 | 6 | // let variableAlmacenar = "TOKEN_SEGURO"; 7 | 8 | // sessionStorage.setItem("token", variableAlmacenar); 9 | // let textoAlmacenado = localStorage.getItem("token"); 10 | //console.log(textoAlmacenado) 11 | 12 | //================ LOCAL STORAGE ================ 13 | // let variableAlmacenar = "TOKEN_SEGURO"; 14 | 15 | // localStorage.setItem("token_ls", variableAlmacenar); 16 | // let textoAlmacenado = localStorage.getItem("token_ls"); 17 | // console.log(textoAlmacenado) 18 | 19 | //================ RECORRER LOCAL STORAGE O SESSION STORAGE ================ 20 | // let tokenAlmacenar = "TOKEN_SEGURO"; 21 | // let usuarioAlmacenar = "Jesus_B"; 22 | 23 | // localStorage.setItem("token_ls", tokenAlmacenar); 24 | // localStorage.setItem("usuario_ls", usuarioAlmacenar); 25 | 26 | // for (let i = 0; i < localStorage.length; i++) { 27 | // let clave = localStorage.key(i); 28 | // console.log("Clave: " + clave); 29 | // console.log("Valor: " + localStorage.getItem(clave)); 30 | // } 31 | 32 | //================ ELIMINAR ELEMENTOS DEL LOCAL STORAGE O SESSION STORAGE ================ 33 | 34 | // localStorage.removeItem("token_ls"); 35 | // localStorage.clear(); 36 | 37 | //================ AGREGAR OBJETO AL LOCAL STORAGE O SESSION STORAGE ================ 38 | // const listaProductos = [ 39 | // { 40 | // id: 1, 41 | // nombre: "Laptop", 42 | // precioCompra: "800", 43 | // precioVenta: "1100", 44 | // cantidad: 2, 45 | // }, 46 | // { 47 | // id: 2, 48 | // nombre: "PC", 49 | // precioCompra: "900", 50 | // precioVenta: "1500", 51 | // cantidad: 3, 52 | // }, 53 | // ]; 54 | 55 | // let listaProductosJSON = JSON.stringify(listaProductos); 56 | // localStorage.setItem("arrayProductos", listaProductosJSON); 57 | 58 | // let productosAlmacenados = localStorage.getItem("arrayProductos"); 59 | // console.log(typeof productosAlmacenados, productosAlmacenados); 60 | 61 | // let productosArray = JSON.parse(productosAlmacenados); 62 | // console.log(typeof productosArray, productosArray); 63 | 64 | //================ EJEMPLO COMPLETO ================ 65 | 66 | // Variables de información 67 | let productos = []; 68 | let usuario; 69 | 70 | // Variables para elementos de autenticación y usuario 71 | 72 | let formularioIdentificacion; 73 | let contenedorIdentificacion; 74 | let contenedorUsuario; 75 | let textoUsuario; 76 | let limpiarStorage; 77 | 78 | // Variables para formulario de productos 79 | let formulario; 80 | let inputId; 81 | let inputNombre; 82 | let inputPrecioCompra; 83 | let inputPrecioVenta; 84 | let inputCantidad; 85 | let contenedorProductos; 86 | 87 | class Producto { 88 | constructor(id, nombre, precioCompra, precioVenta, cantidad) { 89 | this.id = id; 90 | this.nombre = nombre.toUpperCase(); 91 | this.precioCompra = precioCompra; 92 | this.precioVenta = precioVenta; 93 | this.cantidad = cantidad; 94 | } 95 | } 96 | 97 | function inicializarElementos() { 98 | formularioIdentificacion = document.getElementById( 99 | "formularioIdentificacion" 100 | ); 101 | inputUsuario = document.getElementById("inputUsuario"); 102 | contenedorIdentificacion = document.getElementById( 103 | "contenedorIdentificacion" 104 | ); 105 | contenedorUsuario = document.getElementById("contenedorUsuario"); 106 | textoUsuario = document.getElementById("textoUsuario"); 107 | 108 | 109 | limpiarStorage = document.getElementById("limpiarStorage"); 110 | 111 | formulario = document.getElementById("formulario"); 112 | inputId = document.getElementById("inputId"); 113 | inputNombre = document.getElementById("inputNombreProducto"); 114 | inputPrecioCompra = document.getElementById("inputPrecioCompra"); 115 | inputPrecioVenta = document.getElementById("inputPrecioVenta"); 116 | inputCantidad = document.getElementById("inputCantidad"); 117 | contenedorProductos = document.getElementById("contenedorProductos"); 118 | } 119 | 120 | function inicializarEventos() { 121 | formulario.onsubmit = (event) => validarFormulario(event); 122 | formularioIdentificacion.onsubmit = (event) => identificarUsuario(event); 123 | limpiarStorage.onclick = eliminarStorage; 124 | } 125 | 126 | function eliminarStorage() { 127 | localStorage.clear(); 128 | usuario = ""; 129 | productos = []; 130 | mostrarFormularioIdentificacion(); 131 | pintarProductos(); 132 | } 133 | 134 | function identificarUsuario(event) { 135 | event.preventDefault(); 136 | usuario = inputUsuario.value; 137 | formularioIdentificacion.reset(); 138 | actualizarUsuarioStorage(); 139 | mostrarTextoUsuario(); 140 | } 141 | 142 | function mostrarTextoUsuario() { 143 | contenedorIdentificacion.hidden = true; 144 | contenedorUsuario.hidden = false; 145 | textoUsuario.innerHTML += ` ${usuario}`; 146 | } 147 | 148 | function mostrarFormularioIdentificacion() { 149 | contenedorIdentificacion.hidden = false; 150 | contenedorUsuario.hidden = true; 151 | textoUsuario.innerHTML = ``; 152 | } 153 | 154 | function validarFormulario(event) { 155 | event.preventDefault(); 156 | if (usuario) { 157 | let idProducto = inputId.value; 158 | let nombre = inputNombre.value; 159 | let precioCompra = parseFloat(inputPrecioCompra.value); 160 | let precioVenta = parseFloat(inputPrecioVenta.value); 161 | let cantidad = parseInt(inputCantidad.value); 162 | 163 | const idExiste = productos.some((producto) => producto.id === idProducto); 164 | if (!idExiste) { 165 | let producto = new Producto( 166 | idProducto, 167 | nombre, 168 | precioCompra, 169 | precioVenta, 170 | cantidad 171 | ); 172 | 173 | productos.push(producto); 174 | formulario.reset(); 175 | actualizarProductosStorage(); 176 | pintarProductos(); 177 | } else { 178 | alert("El id ya existe"); 179 | } 180 | } else { 181 | alert("Identifíquese antes de agregar un producto"); 182 | } 183 | } 184 | 185 | function eliminarProducto(idProducto) { 186 | let columnaBorrar = document.getElementById(`columna-${idProducto}`); 187 | let indiceBorrar = productos.findIndex( 188 | (producto) => Number(producto.id) === Number(idProducto) 189 | ); 190 | 191 | productos.splice(indiceBorrar, 1); 192 | columnaBorrar.remove(); 193 | actualizarProductosStorage(); 194 | } 195 | 196 | function pintarProductos() { 197 | contenedorProductos.innerHTML = ""; 198 | productos.forEach((producto) => { 199 | let column = document.createElement("div"); 200 | column.className = "col-md-4 mt-3"; 201 | column.id = `columna-${producto.id}`; 202 | column.innerHTML = ` 203 |
204 |
205 |

ID: 206 | ${producto.id} 207 |

208 |

Nombre: 209 | ${producto.nombre} 210 |

211 |

Precio compra: 212 | ${producto.precioCompra} 213 |

214 |

Precio venta: 215 | ${producto.precioVenta} 216 |

217 |

Cantidad: 218 | ${producto.cantidad} 219 |

220 |
221 | 224 |
`; 225 | 226 | contenedorProductos.append(column); 227 | 228 | let botonEliminar = document.getElementById(`botonEliminar-${producto.id}`); 229 | botonEliminar.onclick = () => eliminarProducto(producto.id); 230 | }); 231 | } 232 | 233 | function actualizarProductosStorage() { 234 | let productosJSON = JSON.stringify(productos); 235 | localStorage.setItem("productos", productosJSON); 236 | } 237 | 238 | function actualizarUsuarioStorage() { 239 | localStorage.setItem("usuario", usuario); 240 | } 241 | 242 | function obtenerProductosStorage() { 243 | let productosJSON = localStorage.getItem("productos"); 244 | if (productosJSON) { 245 | productos = JSON.parse(productosJSON); 246 | pintarProductos(); 247 | } 248 | } 249 | 250 | function obtenerUsuarioStorage() { 251 | let usuarioAlmacenado = localStorage.getItem("usuario"); 252 | if (usuarioAlmacenado) { 253 | usuario = usuarioAlmacenado; 254 | mostrarTextoUsuario(); 255 | } 256 | } 257 | 258 | function main() { 259 | inicializarElementos(); 260 | inicializarEventos(); 261 | obtenerProductosStorage(); 262 | obtenerUsuarioStorage(); 263 | } 264 | 265 | main(); 266 | -------------------------------------------------------------------------------- /After 3 (Storage y JSON)/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 14 | 15 | 16 |
17 |
18 |
19 | 22 | 25 |
26 |
27 | 30 |
31 |

Identificate

32 |
33 |
34 |
35 |
36 | 37 | 43 |
44 |
45 |
46 | 49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 | 63 | 138 | 143 | 144 | 145 | 146 | -------------------------------------------------------------------------------- /After 3 (Storage y JSON)/index.js: -------------------------------------------------------------------------------- 1 | //================ EJEMPLO COMPLETO ================ 2 | 3 | // Variables de información 4 | let productos = []; 5 | let usuario; 6 | 7 | // Variables para elementos de autenticación y usuario 8 | 9 | let formularioIdentificacion; 10 | let contenedorIdentificacion; 11 | let contenedorUsuario; 12 | let textoUsuario; 13 | let botonLimpiarStorage; 14 | 15 | // Variables para formulario de productos 16 | let modalAddProduct; 17 | let botonAgregarProducto; 18 | let formulario; 19 | let inputId; 20 | let inputNombre; 21 | let inputPrecioCompra; 22 | let inputPrecioVenta; 23 | let inputCantidad; 24 | let contenedorProductos; 25 | let botonesCerrarModalAgregarProducto; 26 | let modal 27 | 28 | class Producto { 29 | constructor(id, nombre, precioCompra, precioVenta, cantidad) { 30 | this.id = id; 31 | this.nombre = nombre.toUpperCase(); 32 | this.precioCompra = precioCompra; 33 | this.precioVenta = precioVenta; 34 | this.cantidad = cantidad; 35 | } 36 | } 37 | 38 | function inicializarElementos() { 39 | formularioIdentificacion = document.getElementById( 40 | "formularioIdentificacion" 41 | ); 42 | inputUsuario = document.getElementById("inputUsuario"); 43 | contenedorIdentificacion = document.getElementById( 44 | "contenedorIdentificacion" 45 | ); 46 | contenedorUsuario = document.getElementById("contenedorUsuario"); 47 | textoUsuario = document.getElementById("textoUsuario"); 48 | 49 | botonLimpiarStorage = document.getElementById("limpiarStorage"); 50 | formulario = document.getElementById("formularioAgregarProducto"); 51 | inputId = document.getElementById("inputId"); 52 | inputNombre = document.getElementById("inputNombreProducto"); 53 | inputPrecioCompra = document.getElementById("inputPrecioCompra"); 54 | inputPrecioVenta = document.getElementById("inputPrecioVenta"); 55 | inputCantidad = document.getElementById("inputCantidad"); 56 | contenedorProductos = document.getElementById("contenedorProductos"); 57 | 58 | botonesCerrarModalAgregarProducto = document.getElementsByClassName( 59 | "btnCerrarModalAgregarProducto" 60 | ); 61 | modalAddProduct = document.getElementById("modalAddProduct"); 62 | botonAgregarProducto = document.getElementById("btnAgregarProducto"); 63 | modal = new bootstrap.Modal(modalAddProduct); 64 | } 65 | 66 | function inicializarEventos() { 67 | formulario.onsubmit = (event) => validarFormulario(event); 68 | formularioIdentificacion.onsubmit = (event) => identificarUsuario(event); 69 | botonLimpiarStorage.onclick = eliminarStorage; 70 | botonAgregarProducto.onclick = abrirModalAgregarProducto; 71 | 72 | for (const boton of botonesCerrarModalAgregarProducto) { 73 | boton.onclick = cerrarModalAgregarProducto; 74 | } 75 | } 76 | 77 | function abrirModalAgregarProducto() { 78 | if (usuario) { 79 | modal.show(); 80 | } else { 81 | alert("Identifíquese antes de agregar un producto"); 82 | } 83 | } 84 | 85 | function cerrarModalAgregarProducto() { 86 | formulario.reset(); 87 | modal.hide(); 88 | } 89 | 90 | function eliminarStorage() { 91 | localStorage.clear(); 92 | usuario = ""; 93 | productos = []; 94 | mostrarFormularioIdentificacion(); 95 | pintarProductos(); 96 | } 97 | 98 | function identificarUsuario(event) { 99 | event.preventDefault(); 100 | usuario = inputUsuario.value; 101 | formularioIdentificacion.reset(); 102 | actualizarUsuarioStorage(); 103 | mostrarTextoUsuario(); 104 | } 105 | 106 | function mostrarTextoUsuario() { 107 | contenedorIdentificacion.hidden = true; 108 | contenedorUsuario.hidden = false; 109 | textoUsuario.innerHTML += ` ${usuario}`; 110 | } 111 | 112 | function mostrarFormularioIdentificacion() { 113 | contenedorIdentificacion.hidden = false; 114 | contenedorUsuario.hidden = true; 115 | textoUsuario.innerHTML = ``; 116 | } 117 | 118 | function validarFormulario(event) { 119 | event.preventDefault(); 120 | let idProducto = inputId.value; 121 | let nombre = inputNombre.value; 122 | let precioCompra = parseFloat(inputPrecioCompra.value); 123 | let precioVenta = parseFloat(inputPrecioVenta.value); 124 | let cantidad = parseInt(inputCantidad.value); 125 | 126 | const idExiste = productos.some((producto) => producto.id === idProducto); 127 | if (!idExiste) { 128 | let producto = new Producto( 129 | idProducto, 130 | nombre, 131 | precioCompra, 132 | precioVenta, 133 | cantidad 134 | ); 135 | 136 | productos.push(producto); 137 | formulario.reset(); 138 | alert("Producto agregado exitosamente"); 139 | actualizarProductosStorage(); 140 | pintarProductos(); 141 | } else { 142 | alert("El id ya existe"); 143 | } 144 | } 145 | 146 | function eliminarProducto(idProducto) { 147 | let columnaBorrar = document.getElementById(`columna-${idProducto}`); 148 | let indiceBorrar = productos.findIndex( 149 | (producto) => Number(producto.id) === Number(idProducto) 150 | ); 151 | 152 | productos.splice(indiceBorrar, 1); 153 | columnaBorrar.remove(); 154 | actualizarProductosStorage(); 155 | } 156 | 157 | function pintarProductos() { 158 | contenedorProductos.innerHTML = ""; 159 | productos.forEach((producto) => { 160 | let column = document.createElement("div"); 161 | column.className = "col-md-4 mt-3"; 162 | column.id = `columna-${producto.id}`; 163 | column.innerHTML = ` 164 |
165 |
166 |

ID: 167 | ${producto.id} 168 |

169 |

Nombre: 170 | ${producto.nombre} 171 |

172 |

Precio compra: 173 | ${producto.precioCompra} 174 |

175 |

Precio venta: 176 | ${producto.precioVenta} 177 |

178 |

Cantidad: 179 | ${producto.cantidad} 180 |

181 |
182 | 185 |
`; 186 | 187 | contenedorProductos.append(column); 188 | 189 | let botonEliminar = document.getElementById(`botonEliminar-${producto.id}`); 190 | botonEliminar.onclick = () => eliminarProducto(producto.id); 191 | }); 192 | } 193 | 194 | function actualizarProductosStorage() { 195 | let productosJSON = JSON.stringify(productos); 196 | localStorage.setItem("productos", productosJSON); 197 | } 198 | 199 | function actualizarUsuarioStorage() { 200 | localStorage.setItem("usuario", usuario); 201 | } 202 | 203 | function obtenerProductosStorage() { 204 | let productosJSON = localStorage.getItem("productos"); 205 | if (productosJSON) { 206 | productos = JSON.parse(productosJSON); 207 | pintarProductos(); 208 | } 209 | } 210 | 211 | function obtenerUsuarioStorage() { 212 | let usuarioAlmacenado = localStorage.getItem("usuario"); 213 | if (usuarioAlmacenado) { 214 | usuario = usuarioAlmacenado; 215 | mostrarTextoUsuario(); 216 | } 217 | } 218 | 219 | function main() { 220 | inicializarElementos(); 221 | inicializarEventos(); 222 | obtenerProductosStorage(); 223 | obtenerUsuarioStorage(); 224 | } 225 | 226 | main(); 227 | -------------------------------------------------------------------------------- /After 4 (AJAX)/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "liveServer.settings.port": 5501 3 | } -------------------------------------------------------------------------------- /After 4 (AJAX)/ejemplo_base/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 14 | 15 | 16 | 17 | 18 |
19 |
20 |
21 | 24 | 27 |
28 |
29 | 32 |
33 |

Identificate

34 |
35 |
36 |
37 |
38 | 39 | 45 |
46 |
47 |
48 | 51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 | 65 | 140 | 145 | 146 | 147 | 148 | 149 | 150 | -------------------------------------------------------------------------------- /After 4 (AJAX)/ejemplo_base/index.js: -------------------------------------------------------------------------------- 1 | //================ EJEMPLO COMPLETO ================ 2 | 3 | // Variables de información 4 | let productos = []; 5 | let usuario; 6 | 7 | // Variables para elementos de autenticación y usuario 8 | 9 | let formularioIdentificacion; 10 | let contenedorIdentificacion; 11 | let contenedorUsuario; 12 | let textoUsuario; 13 | let botonLimpiarStorage; 14 | 15 | // Variables para formulario de productos 16 | let modalAddProduct; 17 | let botonAgregarProducto; 18 | let formulario; 19 | let inputId; 20 | let inputNombre; 21 | let inputPrecioCompra; 22 | let inputPrecioVenta; 23 | let inputCantidad; 24 | let contenedorProductos; 25 | let botonesCerrarModalAgregarProducto; 26 | let modal; 27 | 28 | class Producto { 29 | constructor(id, nombre, precioCompra, precioVenta, cantidad) { 30 | this.id = id; 31 | this.nombre = nombre.toUpperCase(); 32 | this.precioCompra = precioCompra; 33 | this.precioVenta = precioVenta; 34 | this.cantidad = cantidad; 35 | } 36 | } 37 | 38 | function inicializarElementos() { 39 | formularioIdentificacion = document.getElementById( 40 | "formularioIdentificacion" 41 | ); 42 | inputUsuario = document.getElementById("inputUsuario"); 43 | contenedorIdentificacion = document.getElementById( 44 | "contenedorIdentificacion" 45 | ); 46 | contenedorUsuario = document.getElementById("contenedorUsuario"); 47 | textoUsuario = document.getElementById("textoUsuario"); 48 | 49 | botonLimpiarStorage = document.getElementById("limpiarStorage"); 50 | formulario = document.getElementById("formularioAgregarProducto"); 51 | inputId = document.getElementById("inputId"); 52 | inputNombre = document.getElementById("inputNombreProducto"); 53 | inputPrecioCompra = document.getElementById("inputPrecioCompra"); 54 | inputPrecioVenta = document.getElementById("inputPrecioVenta"); 55 | inputCantidad = document.getElementById("inputCantidad"); 56 | contenedorProductos = document.getElementById("contenedorProductos"); 57 | 58 | botonesCerrarModalAgregarProducto = document.getElementsByClassName( 59 | "btnCerrarModalAgregarProducto" 60 | ); 61 | modalAddProduct = document.getElementById("modalAddProduct"); 62 | botonAgregarProducto = document.getElementById("btnAgregarProducto"); 63 | modal = new bootstrap.Modal(modalAddProduct); 64 | } 65 | 66 | function inicializarEventos() { 67 | formulario.onsubmit = (event) => validarFormulario(event); 68 | formularioIdentificacion.onsubmit = (event) => identificarUsuario(event); 69 | botonLimpiarStorage.onclick = eliminarStorage; 70 | botonAgregarProducto.onclick = abrirModalAgregarProducto; 71 | 72 | for (const boton of botonesCerrarModalAgregarProducto) { 73 | boton.onclick = cerrarModalAgregarProducto; 74 | } 75 | } 76 | 77 | function abrirModalAgregarProducto() { 78 | if (usuario) { 79 | modal.show(); 80 | } else { 81 | alert("Identifíquese antes de agregar un producto"); 82 | } 83 | } 84 | 85 | function cerrarModalAgregarProducto() { 86 | formulario.reset(); 87 | modal.hide(); 88 | } 89 | 90 | function eliminarStorage() { 91 | localStorage.clear(); 92 | usuario = ""; 93 | productos = []; 94 | mostrarFormularioIdentificacion(); 95 | pintarProductos(); 96 | } 97 | 98 | function identificarUsuario(event) { 99 | event.preventDefault(); 100 | usuario = inputUsuario.value; 101 | formularioIdentificacion.reset(); 102 | actualizarUsuarioStorage(); 103 | mostrarTextoUsuario(); 104 | } 105 | 106 | function mostrarTextoUsuario() { 107 | contenedorIdentificacion.hidden = true; 108 | contenedorUsuario.hidden = false; 109 | textoUsuario.innerHTML += ` ${usuario}`; 110 | } 111 | 112 | function mostrarFormularioIdentificacion() { 113 | contenedorIdentificacion.hidden = false; 114 | contenedorUsuario.hidden = true; 115 | textoUsuario.innerHTML = ``; 116 | } 117 | 118 | function validarFormulario(event) { 119 | event.preventDefault(); 120 | let idProducto = inputId.value; 121 | let nombre = inputNombre.value; 122 | let precioCompra = parseFloat(inputPrecioCompra.value); 123 | let precioVenta = parseFloat(inputPrecioVenta.value); 124 | let cantidad = parseInt(inputCantidad.value); 125 | 126 | const idExiste = productos.some((producto) => producto.id === idProducto); 127 | if (!idExiste) { 128 | let producto = new Producto( 129 | idProducto, 130 | nombre, 131 | precioCompra, 132 | precioVenta, 133 | cantidad 134 | ); 135 | 136 | productos.push(producto); 137 | formulario.reset(); 138 | actualizarProductosStorage(); 139 | pintarProductos(); 140 | mostrarMensajeConfirmacion( 141 | `El producto ${nombre} fue agregado exitosamente`, 142 | "info" 143 | ); 144 | } else { 145 | alert("El id ya existe"); 146 | } 147 | } 148 | 149 | function confirmarEliminacion(idProducto) { 150 | Swal.fire({ 151 | icon: "question", 152 | title: "¿Estas seguro que quieres eliminar el producto?", 153 | showCancelButton: true, 154 | confirmButtonText: "Eliminar", 155 | cancelButtonText: "Cancelar", 156 | }).then((result) => { 157 | if (result.isConfirmed) { 158 | eliminarProducto(idProducto); 159 | } 160 | }); 161 | } 162 | 163 | function eliminarProducto(idProducto) { 164 | let columnaBorrar = document.getElementById(`columna-${idProducto}`); 165 | let indiceBorrar = productos.findIndex( 166 | (producto) => Number(producto.id) === Number(idProducto) 167 | ); 168 | 169 | let nombreProductoEliminado = productos[indiceBorrar].nombre; 170 | productos.splice(indiceBorrar, 1); 171 | columnaBorrar.remove(); 172 | actualizarProductosStorage(); 173 | mostrarMensajeConfirmacion( 174 | `El producto ${nombreProductoEliminado} fue eliminado exitosamente`, 175 | "danger" 176 | ); 177 | } 178 | 179 | function pintarProductos() { 180 | contenedorProductos.innerHTML = ""; 181 | productos.forEach((producto) => { 182 | let column = document.createElement("div"); 183 | column.className = "col-md-4 mt-3"; 184 | column.id = `columna-${producto.id}`; 185 | column.innerHTML = ` 186 |
187 |
188 |

ID: 189 | ${producto.id} 190 |

191 |

Nombre: 192 | ${producto.nombre} 193 |

194 |

Precio compra: 195 | ${producto.precioCompra} 196 |

197 |

Precio venta: 198 | ${producto.precioVenta} 199 |

200 |

Cantidad: 201 | ${producto.cantidad} 202 |

203 |
204 | 207 |
`; 208 | 209 | contenedorProductos.append(column); 210 | 211 | let botonEliminar = document.getElementById(`botonEliminar-${producto.id}`); 212 | botonEliminar.onclick = () => confirmarEliminacion(producto.id); 213 | }); 214 | } 215 | 216 | function actualizarProductosStorage() { 217 | let productosJSON = JSON.stringify(productos); 218 | localStorage.setItem("productos", productosJSON); 219 | } 220 | 221 | function actualizarUsuarioStorage() { 222 | localStorage.setItem("usuario", usuario); 223 | } 224 | 225 | function obtenerProductosStorage() { 226 | let productosJSON = localStorage.getItem("productos"); 227 | if (productosJSON) { 228 | productos = JSON.parse(productosJSON); 229 | pintarProductos(); 230 | } 231 | } 232 | 233 | function obtenerUsuarioStorage() { 234 | let usuarioAlmacenado = localStorage.getItem("usuario"); 235 | if (usuarioAlmacenado) { 236 | usuario = usuarioAlmacenado; 237 | mostrarTextoUsuario(); 238 | } 239 | } 240 | 241 | function mostrarMensajeConfirmacion(mensaje, clase) { 242 | Toastify({ 243 | text: mensaje, 244 | duration: 30000, 245 | close: true, 246 | gravity: "top", 247 | position: "right", 248 | className: clase, 249 | }).showToast(); 250 | } 251 | 252 | async function consultarProductosServer() { 253 | try { 254 | const response = await fetch( 255 | "https://6244e0467701ec8f724a5a7f.mockapi.io/api/productos" 256 | ); 257 | const data = await response.json(); 258 | productos = [...data]; 259 | pintarProductos(); 260 | } catch (error) { 261 | console.log(error); 262 | } 263 | } 264 | 265 | function main() { 266 | inicializarElementos(); 267 | inicializarEventos(); 268 | consultarProductosServer(); 269 | //obtenerProductosStorage(); 270 | obtenerUsuarioStorage(); 271 | } 272 | 273 | main(); 274 | -------------------------------------------------------------------------------- /After 4 (AJAX)/ejemplo_base/productos.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "nombre": "Licensed Frozen Salad", 4 | "cantidad": 49, 5 | "precioVenta": "537.00", 6 | "precioCompra": "784.00", 7 | "fecha": "2022-04-04T06:08:01.498Z", 8 | "id": "7" 9 | }, 10 | { 11 | "nombre": "Licensed Fresh Bike", 12 | "cantidad": 91, 13 | "precioVenta": "989.00", 14 | "precioCompra": "816.00", 15 | "fecha": "2022-10-05T09:06:59.703Z", 16 | "id": "8" 17 | }, 18 | { 19 | "nombre": "Sleek Rubber Pants", 20 | "cantidad": 19, 21 | "precioVenta": "384.00", 22 | "precioCompra": "929.00", 23 | "fecha": "2022-10-05T16:43:45.364Z", 24 | "id": "9" 25 | }, 26 | { 27 | "nombre": "Recycled Fresh Shoes", 28 | "cantidad": 95, 29 | "precioVenta": "417.00", 30 | "precioCompra": "450.00", 31 | "fecha": "2022-10-05T11:01:19.684Z", 32 | "id": "10" 33 | }, 34 | { 35 | "nombre": "Fantastic Frozen Cheese", 36 | "cantidad": 12, 37 | "precioVenta": "41.00", 38 | "precioCompra": "692.00", 39 | "fecha": "2022-10-05T05:41:58.508Z", 40 | "id": "11" 41 | }, 42 | { 43 | "nombre": "Handmade Granite Ball", 44 | "cantidad": 73, 45 | "precioVenta": "511.00", 46 | "precioCompra": "626.00", 47 | "fecha": "2022-10-05T10:52:52.282Z", 48 | "id": "12" 49 | }, 50 | { 51 | "nombre": "Gorgeous Fresh Shoes", 52 | "cantidad": 13, 53 | "precioVenta": "723.00", 54 | "precioCompra": "756.00", 55 | "fecha": "2022-10-05T15:11:39.565Z", 56 | "id": "13" 57 | }, 58 | { 59 | "nombre": "Bespoke Soft Cheese", 60 | "cantidad": 59, 61 | "precioVenta": "662.00", 62 | "precioCompra": "378.00", 63 | "fecha": "2022-10-05T22:19:36.777Z", 64 | "id": "14" 65 | }, 66 | { 67 | "nombre": "Tasty Frozen Ball", 68 | "cantidad": 88, 69 | "precioVenta": "261.00", 70 | "precioCompra": "31.00", 71 | "fecha": "2022-10-05T23:20:32.106Z", 72 | "id": "15" 73 | }, 74 | { 75 | "nombre": "Electronic Concrete Computer", 76 | "cantidad": 96, 77 | "precioVenta": "562.00", 78 | "precioCompra": "557.00", 79 | "fecha": "2022-10-05T23:40:25.696Z", 80 | "id": "16" 81 | }, 82 | { 83 | "nombre": "Handcrafted Rubber Fish", 84 | "cantidad": 19, 85 | "precioVenta": "684.00", 86 | "precioCompra": "34.00", 87 | "fecha": "2022-10-05T06:59:45.213Z", 88 | "id": "17" 89 | }, 90 | { 91 | "nombre": "Recycled Frozen Hat", 92 | "cantidad": 55, 93 | "precioVenta": "3.00", 94 | "precioCompra": "349.00", 95 | "fecha": "2022-10-05T15:22:08.468Z", 96 | "id": "18" 97 | }, 98 | { 99 | "nombre": "Fantastic Fresh Sausages", 100 | "cantidad": 18, 101 | "precioVenta": "336.00", 102 | "precioCompra": "637.00", 103 | "fecha": "2022-10-05T11:52:15.595Z", 104 | "id": "19" 105 | }, 106 | { 107 | "nombre": "Refined Wooden Bike", 108 | "cantidad": 16, 109 | "precioVenta": "32.00", 110 | "precioCompra": "439.00", 111 | "fecha": "2022-10-05T06:00:37.481Z", 112 | "id": "20" 113 | }, 114 | { 115 | "nombre": "Electronic Bronze Fish", 116 | "cantidad": 57, 117 | "precioVenta": "556.00", 118 | "precioCompra": "883.00", 119 | "fecha": "2022-10-05T18:15:54.069Z", 120 | "id": "21" 121 | }, 122 | { 123 | "nombre": "Handcrafted Concrete Fish", 124 | "cantidad": 74, 125 | "precioVenta": "571.00", 126 | "precioCompra": "530.00", 127 | "fecha": "2022-10-05T20:29:51.583Z", 128 | "id": "22" 129 | }, 130 | { 131 | "nombre": "Ergonomic Metal Salad", 132 | "cantidad": 73, 133 | "precioVenta": "590.00", 134 | "precioCompra": "707.00", 135 | "fecha": "2022-10-05T08:38:09.457Z", 136 | "id": "23" 137 | }, 138 | { 139 | "nombre": "Fantastic Frozen Chicken", 140 | "cantidad": 77, 141 | "precioVenta": "668.00", 142 | "precioCompra": "205.00", 143 | "fecha": "2022-10-05T14:20:06.698Z", 144 | "id": "24" 145 | }, 146 | { 147 | "nombre": "Luxurious Soft Pizza", 148 | "cantidad": 27, 149 | "precioVenta": "919.00", 150 | "precioCompra": "356.00", 151 | "fecha": "2022-10-05T04:34:09.423Z", 152 | "id": "25" 153 | }, 154 | { 155 | "nombre": "Ergonomic Granite Bacon", 156 | "cantidad": 24, 157 | "precioVenta": "947.00", 158 | "precioCompra": "530.00", 159 | "fecha": "2022-10-05T22:23:51.762Z", 160 | "id": "26" 161 | }, 162 | { 163 | "nombre": "Luxurious Concrete Tuna", 164 | "cantidad": 81, 165 | "precioVenta": "888.00", 166 | "precioCompra": "249.00", 167 | "fecha": "2022-10-05T06:24:17.250Z", 168 | "id": "27" 169 | } 170 | ] 171 | -------------------------------------------------------------------------------- /After 4 (AJAX)/ejemplo_base/style.css: -------------------------------------------------------------------------------- 1 | .info{ 2 | background: blueviolet; 3 | } -------------------------------------------------------------------------------- /After 4 (AJAX)/ejemplo_completo/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 14 | 15 | 16 | 17 | 18 |
19 |
20 |
21 | 24 | 27 |
28 |
29 | 32 |
33 |

Identificate

34 |
35 |
36 |
37 |
38 | 39 | 45 |
46 |
47 |
48 | 51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 | 65 | 140 | 145 | 146 | 147 | 148 | 149 | 150 | -------------------------------------------------------------------------------- /After 4 (AJAX)/ejemplo_completo/productos.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "nombre": "Licensed Frozen Salad", 4 | "cantidad": 49, 5 | "precioVenta": "537.00", 6 | "precioCompra": "784.00", 7 | "fecha": "2022-04-04T06:08:01.498Z", 8 | "id": "7" 9 | }, 10 | { 11 | "nombre": "Licensed Fresh Bike", 12 | "cantidad": 91, 13 | "precioVenta": "989.00", 14 | "precioCompra": "816.00", 15 | "fecha": "2022-10-05T09:06:59.703Z", 16 | "id": "8" 17 | }, 18 | { 19 | "nombre": "Sleek Rubber Pants", 20 | "cantidad": 19, 21 | "precioVenta": "384.00", 22 | "precioCompra": "929.00", 23 | "fecha": "2022-10-05T16:43:45.364Z", 24 | "id": "9" 25 | }, 26 | { 27 | "nombre": "Recycled Fresh Shoes", 28 | "cantidad": 95, 29 | "precioVenta": "417.00", 30 | "precioCompra": "450.00", 31 | "fecha": "2022-10-05T11:01:19.684Z", 32 | "id": "10" 33 | }, 34 | { 35 | "nombre": "Fantastic Frozen Cheese", 36 | "cantidad": 12, 37 | "precioVenta": "41.00", 38 | "precioCompra": "692.00", 39 | "fecha": "2022-10-05T05:41:58.508Z", 40 | "id": "11" 41 | }, 42 | { 43 | "nombre": "Handmade Granite Ball", 44 | "cantidad": 73, 45 | "precioVenta": "511.00", 46 | "precioCompra": "626.00", 47 | "fecha": "2022-10-05T10:52:52.282Z", 48 | "id": "12" 49 | }, 50 | { 51 | "nombre": "Gorgeous Fresh Shoes", 52 | "cantidad": 13, 53 | "precioVenta": "723.00", 54 | "precioCompra": "756.00", 55 | "fecha": "2022-10-05T15:11:39.565Z", 56 | "id": "13" 57 | }, 58 | { 59 | "nombre": "Bespoke Soft Cheese", 60 | "cantidad": 59, 61 | "precioVenta": "662.00", 62 | "precioCompra": "378.00", 63 | "fecha": "2022-10-05T22:19:36.777Z", 64 | "id": "14" 65 | }, 66 | { 67 | "nombre": "Tasty Frozen Ball", 68 | "cantidad": 88, 69 | "precioVenta": "261.00", 70 | "precioCompra": "31.00", 71 | "fecha": "2022-10-05T23:20:32.106Z", 72 | "id": "15" 73 | }, 74 | { 75 | "nombre": "Electronic Concrete Computer", 76 | "cantidad": 96, 77 | "precioVenta": "562.00", 78 | "precioCompra": "557.00", 79 | "fecha": "2022-10-05T23:40:25.696Z", 80 | "id": "16" 81 | }, 82 | { 83 | "nombre": "Handcrafted Rubber Fish", 84 | "cantidad": 19, 85 | "precioVenta": "684.00", 86 | "precioCompra": "34.00", 87 | "fecha": "2022-10-05T06:59:45.213Z", 88 | "id": "17" 89 | }, 90 | { 91 | "nombre": "Recycled Frozen Hat", 92 | "cantidad": 55, 93 | "precioVenta": "3.00", 94 | "precioCompra": "349.00", 95 | "fecha": "2022-10-05T15:22:08.468Z", 96 | "id": "18" 97 | }, 98 | { 99 | "nombre": "Fantastic Fresh Sausages", 100 | "cantidad": 18, 101 | "precioVenta": "336.00", 102 | "precioCompra": "637.00", 103 | "fecha": "2022-10-05T11:52:15.595Z", 104 | "id": "19" 105 | }, 106 | { 107 | "nombre": "Refined Wooden Bike", 108 | "cantidad": 16, 109 | "precioVenta": "32.00", 110 | "precioCompra": "439.00", 111 | "fecha": "2022-10-05T06:00:37.481Z", 112 | "id": "20" 113 | }, 114 | { 115 | "nombre": "Electronic Bronze Fish", 116 | "cantidad": 57, 117 | "precioVenta": "556.00", 118 | "precioCompra": "883.00", 119 | "fecha": "2022-10-05T18:15:54.069Z", 120 | "id": "21" 121 | }, 122 | { 123 | "nombre": "Handcrafted Concrete Fish", 124 | "cantidad": 74, 125 | "precioVenta": "571.00", 126 | "precioCompra": "530.00", 127 | "fecha": "2022-10-05T20:29:51.583Z", 128 | "id": "22" 129 | }, 130 | { 131 | "nombre": "Ergonomic Metal Salad", 132 | "cantidad": 73, 133 | "precioVenta": "590.00", 134 | "precioCompra": "707.00", 135 | "fecha": "2022-10-05T08:38:09.457Z", 136 | "id": "23" 137 | }, 138 | { 139 | "nombre": "Fantastic Frozen Chicken", 140 | "cantidad": 77, 141 | "precioVenta": "668.00", 142 | "precioCompra": "205.00", 143 | "fecha": "2022-10-05T14:20:06.698Z", 144 | "id": "24" 145 | }, 146 | { 147 | "nombre": "Luxurious Soft Pizza", 148 | "cantidad": 27, 149 | "precioVenta": "919.00", 150 | "precioCompra": "356.00", 151 | "fecha": "2022-10-05T04:34:09.423Z", 152 | "id": "25" 153 | }, 154 | { 155 | "nombre": "Ergonomic Granite Bacon", 156 | "cantidad": 24, 157 | "precioVenta": "947.00", 158 | "precioCompra": "530.00", 159 | "fecha": "2022-10-05T22:23:51.762Z", 160 | "id": "26" 161 | }, 162 | { 163 | "nombre": "Luxurious Concrete Tuna", 164 | "cantidad": 81, 165 | "precioVenta": "888.00", 166 | "precioCompra": "249.00", 167 | "fecha": "2022-10-05T06:24:17.250Z", 168 | "id": "27" 169 | } 170 | ] 171 | -------------------------------------------------------------------------------- /After 4 (AJAX)/ejemplo_completo/style.css: -------------------------------------------------------------------------------- 1 | .info{ 2 | background: blueviolet; 3 | } -------------------------------------------------------------------------------- /Clase 1 (Sintaxis)/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /Clase 1 (Sintaxis)/index.js: -------------------------------------------------------------------------------- 1 | //========= DECLARACIÓN Y ASIGNACIÓN DE VARIABLES ========= 2 | 3 | // let nombre = "Jesus"; 4 | // let edad = 25; 5 | // const PI = 3.1416 6 | // PI = 3.14 7 | //========= OPERACIONES CON VARIABLES ========= 8 | 9 | // let calificacionUno = 10; 10 | // let calificacionDos = 5; 11 | // let calificacionTres = 8; 12 | 13 | // const SUMA = calificacionUno + calificacionDos + calificacionTres; 14 | // console.log(SUMA) 15 | 16 | // const RESTA = calificacionUno - calificacionDos - calificacionTres; 17 | // console.log(RESTA) 18 | 19 | // const MULTIPLICACION = calificacionUno * calificacionDos * calificacionTres; 20 | // console.log(MULTIPLICACION) 21 | 22 | // const DIVISION = SUMA/3; 23 | // console.log(DIVISION) 24 | 25 | //========= CONCATENAR STRINGS ========= 26 | 27 | // let palabraUno 28 | // let palabraDos 29 | // let palabraTres 30 | 31 | // palabraUno = "Bienvenidos" 32 | // palabraDos = " al " 33 | // palabraTres = "curso" 34 | 35 | // const FRASE = palabraUno + palabraDos + palabraTres 36 | 37 | // console.log(FRASE) 38 | 39 | 40 | //========= SOLICITAR INFORMACIÓN AL USUARIO ========= 41 | 42 | const NOMBRE = prompt("Ingresa tu nombre") 43 | const ANIO = prompt("Ingresa tu año de nacimiento") 44 | const EDAD = 2022 - ANIO 45 | 46 | const FRASE = "Hola " + NOMBRE + " este año tendrás: " + EDAD + " años" 47 | 48 | console.log(FRASE) 49 | 50 | alert(FRASE) -------------------------------------------------------------------------------- /Clase 10 (Storage y JSON)/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JesusBrito/comision-34015-javascript/63d372d3a93333c1e79978d73ba60ca7f9399bb9/Clase 10 (Storage y JSON)/.DS_Store -------------------------------------------------------------------------------- /Clase 10 (Storage y JSON)/ejemplo_base/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 14 | 15 | 16 |
17 |
18 |
19 |
20 |
21 |
22 |

Ejemplo formulario

23 |
24 |
25 | 26 | 27 |
28 |
29 | 30 | 35 |
36 | 37 |
38 | 39 | 44 |
45 | 46 |
47 | 48 | 49 |
50 | 51 |
52 | 53 | 54 |
55 | 56 |
57 | 58 |
59 |
60 |
61 |
62 |
63 | 68 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /Clase 10 (Storage y JSON)/ejemplo_base/index.js: -------------------------------------------------------------------------------- 1 | let productos = []; 2 | 3 | let formulario; 4 | let inputId; 5 | let inputNombre; 6 | let inputPrecioCompra; 7 | let inputPrecioVenta; 8 | let inputCantidad; 9 | let contenedorProductos; 10 | 11 | class Producto { 12 | constructor(id, nombre, precioCompra, precioVenta, cantidad) { 13 | this.id = id; 14 | this.nombre = nombre.toUpperCase(); 15 | this.precioCompra = precioCompra; 16 | this.precioVenta = precioVenta; 17 | this.cantidad = cantidad; 18 | } 19 | calcularPrecioCompra = () => this.precioCompra * this.cantidad; 20 | calcularPrecioVenta = () => this.precioVenta * this.cantidad; 21 | } 22 | 23 | function inicializarElementos() { 24 | formulario = document.getElementById("formulario"); 25 | inputId = document.getElementById("inputId"); 26 | inputNombre = document.getElementById("inputNombreProducto"); 27 | inputPrecioCompra = document.getElementById("inputPrecioCompra"); 28 | inputPrecioVenta = document.getElementById("inputPrecioVenta"); 29 | inputCantidad = document.getElementById("inputCantidad"); 30 | contenedorProductos = document.getElementById("contenedorProductos"); 31 | } 32 | 33 | function inicializarEventos() { 34 | formulario.onsubmit = (event) => validarFormulario(event); 35 | } 36 | 37 | function validarFormulario(event) { 38 | event.preventDefault(); 39 | let idProducto = inputId.value; 40 | let nombre = inputNombre.value; 41 | let precioCompra = parseFloat(inputPrecioCompra.value); 42 | let precioVenta = parseFloat(inputPrecioVenta.value); 43 | let cantidad = parseInt(inputCantidad.value); 44 | 45 | const idExiste = productos.some((producto) => producto.id === idProducto); 46 | if (!idExiste) { 47 | let producto = new Producto( 48 | idProducto, 49 | nombre, 50 | precioCompra, 51 | precioVenta, 52 | cantidad 53 | ); 54 | 55 | productos.push(producto); 56 | formulario.reset(); 57 | 58 | pintarProductos(); 59 | } else { 60 | alert("El id ya existe"); 61 | } 62 | } 63 | 64 | function eliminarProducto(idProducto) { 65 | let columnaBorrar = document.getElementById(`columna-${idProducto}`); 66 | let indiceBorrar = productos.findIndex( 67 | (producto) => Number(producto.id) === Number(idProducto) 68 | ); 69 | 70 | productos.splice(indiceBorrar, 1); 71 | columnaBorrar.remove(); 72 | } 73 | 74 | function pintarProductos() { 75 | contenedorProductos.innerHTML = ""; 76 | productos.forEach((producto) => { 77 | let column = document.createElement("div"); 78 | column.className = "col-md-4 mt-3"; 79 | column.id = `columna-${producto.id}`; 80 | column.innerHTML = ` 81 |
82 |
83 |

ID: 84 | ${producto.id} 85 |

86 |

Nombre: 87 | ${producto.nombre} 88 |

89 |

Precio compra: 90 | ${producto.precioCompra} 91 |

92 |

Precio venta: 93 | ${producto.precioVenta} 94 |

95 |

Cantidad: 96 | ${producto.cantidad} 97 |

98 |
99 | 102 |
`; 103 | 104 | contenedorProductos.append(column); 105 | 106 | let botonEliminar = document.getElementById(`botonEliminar-${producto.id}`); 107 | botonEliminar.onclick = () => eliminarProducto(producto.id); 108 | }); 109 | } 110 | 111 | function main() { 112 | inicializarElementos(); 113 | inicializarEventos(); 114 | } 115 | 116 | main(); 117 | -------------------------------------------------------------------------------- /Clase 10 (Storage y JSON)/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 14 | 15 | 16 |
17 |
18 |
19 | 22 |
23 |
24 | 27 |
28 |

Identificate

29 |
30 |
31 |
32 |
33 | 34 | 40 |
41 |
42 |
43 | 46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |

Ejemplo formulario

59 |
60 |
61 | 62 | 63 |
64 |
65 | 66 | 72 |
73 | 74 |
75 | 76 | 82 |
83 | 84 |
85 | 86 | 92 |
93 | 94 |
95 | 96 | 102 |
103 | 104 |
105 | 106 |
107 |
108 |
109 |
110 |
111 | 116 | 117 | 118 | 119 | -------------------------------------------------------------------------------- /Clase 10 (Storage y JSON)/index.js: -------------------------------------------------------------------------------- 1 | //================ SESSION STORAGE ================ 2 | //Se utiliza para almacenar información en el navegador, 3 | // esta información se elimina si se cierra el navegador 4 | // o se cierra la pestaña 5 | 6 | // let variableAlmacenar = "TOKEN_SEGURO"; 7 | 8 | // sessionStorage.setItem("token", variableAlmacenar); 9 | // let textoAlmacenado = localStorage.getItem("token"); 10 | //console.log(textoAlmacenado) 11 | 12 | //================ LOCAL STORAGE ================ 13 | // let variableAlmacenar = "TOKEN_SEGURO"; 14 | 15 | // localStorage.setItem("token_ls", variableAlmacenar); 16 | // let textoAlmacenado = localStorage.getItem("token_ls"); 17 | // console.log(textoAlmacenado) 18 | 19 | //================ RECORRER LOCAL STORAGE O SESSION STORAGE ================ 20 | // let tokenAlmacenar = "TOKEN_SEGURO"; 21 | // let usuarioAlmacenar = "Jesus_B"; 22 | 23 | // localStorage.setItem("token_ls", tokenAlmacenar); 24 | // localStorage.setItem("usuario_ls", usuarioAlmacenar); 25 | 26 | // for (let i = 0; i < localStorage.length; i++) { 27 | // let clave = localStorage.key(i); 28 | // console.log("Clave: " + clave); 29 | // console.log("Valor: " + localStorage.getItem(clave)); 30 | // } 31 | 32 | //================ ELIMINAR ELEMENTOS DEL LOCAL STORAGE O SESSION STORAGE ================ 33 | 34 | // localStorage.removeItem("token_ls"); 35 | // localStorage.clear(); 36 | 37 | //================ AGREGAR OBJETO AL LOCAL STORAGE O SESSION STORAGE ================ 38 | // const listaProductos = [ 39 | // { 40 | // id: 1, 41 | // nombre: "Laptop", 42 | // precioCompra: "800", 43 | // precioVenta: "1100", 44 | // cantidad: 2, 45 | // }, 46 | // { 47 | // id: 2, 48 | // nombre: "PC", 49 | // precioCompra: "900", 50 | // precioVenta: "1500", 51 | // cantidad: 3, 52 | // }, 53 | // ]; 54 | 55 | // let listaProductosJSON = JSON.stringify(listaProductos); 56 | // localStorage.setItem("arrayProductos", listaProductosJSON); 57 | 58 | // let productosAlmacenados = localStorage.getItem("arrayProductos"); 59 | // console.log(typeof productosAlmacenados, productosAlmacenados); 60 | 61 | // let productosArray = JSON.parse(productosAlmacenados); 62 | // console.log(typeof productosArray, productosArray); 63 | 64 | //================ EJEMPLO COMPLETO ================ 65 | 66 | // Variables de información 67 | let productos = []; 68 | let usuario; 69 | 70 | // Variables para elementos de autenticación y usuario 71 | 72 | let formularioIdentificacion; 73 | let contenedorIdentificacion; 74 | let contenedorUsuario; 75 | let textoUsuario; 76 | let limpiarStorage; 77 | 78 | // Variables para formulario de productos 79 | let formulario; 80 | let inputId; 81 | let inputNombre; 82 | let inputPrecioCompra; 83 | let inputPrecioVenta; 84 | let inputCantidad; 85 | let contenedorProductos; 86 | 87 | class Producto { 88 | constructor(id, nombre, precioCompra, precioVenta, cantidad) { 89 | this.id = id; 90 | this.nombre = nombre.toUpperCase(); 91 | this.precioCompra = precioCompra; 92 | this.precioVenta = precioVenta; 93 | this.cantidad = cantidad; 94 | } 95 | } 96 | 97 | function inicializarElementos() { 98 | formularioIdentificacion = document.getElementById( 99 | "formularioIdentificacion" 100 | ); 101 | inputUsuario = document.getElementById("inputUsuario"); 102 | contenedorIdentificacion = document.getElementById( 103 | "contenedorIdentificacion" 104 | ); 105 | contenedorUsuario = document.getElementById("contenedorUsuario"); 106 | textoUsuario = document.getElementById("textoUsuario"); 107 | 108 | 109 | limpiarStorage = document.getElementById("limpiarStorage"); 110 | 111 | formulario = document.getElementById("formulario"); 112 | inputId = document.getElementById("inputId"); 113 | inputNombre = document.getElementById("inputNombreProducto"); 114 | inputPrecioCompra = document.getElementById("inputPrecioCompra"); 115 | inputPrecioVenta = document.getElementById("inputPrecioVenta"); 116 | inputCantidad = document.getElementById("inputCantidad"); 117 | contenedorProductos = document.getElementById("contenedorProductos"); 118 | } 119 | 120 | function inicializarEventos() { 121 | formulario.onsubmit = (event) => validarFormulario(event); 122 | formularioIdentificacion.onsubmit = (event) => identificarUsuario(event); 123 | limpiarStorage.onclick = eliminarStorage; 124 | } 125 | 126 | function eliminarStorage() { 127 | localStorage.clear(); 128 | usuario = ""; 129 | productos = []; 130 | mostrarFormularioIdentificacion(); 131 | pintarProductos(); 132 | } 133 | 134 | function identificarUsuario(event) { 135 | event.preventDefault(); 136 | usuario = inputUsuario.value; 137 | formularioIdentificacion.reset(); 138 | actualizarUsuarioStorage(); 139 | mostrarTextoUsuario(); 140 | } 141 | 142 | function mostrarTextoUsuario() { 143 | contenedorIdentificacion.hidden = true; 144 | contenedorUsuario.hidden = false; 145 | textoUsuario.innerHTML += ` ${usuario}`; 146 | } 147 | 148 | function mostrarFormularioIdentificacion() { 149 | contenedorIdentificacion.hidden = false; 150 | contenedorUsuario.hidden = true; 151 | textoUsuario.innerHTML = ``; 152 | } 153 | 154 | function validarFormulario(event) { 155 | event.preventDefault(); 156 | if (usuario) { 157 | let idProducto = inputId.value; 158 | let nombre = inputNombre.value; 159 | let precioCompra = parseFloat(inputPrecioCompra.value); 160 | let precioVenta = parseFloat(inputPrecioVenta.value); 161 | let cantidad = parseInt(inputCantidad.value); 162 | 163 | const idExiste = productos.some((producto) => producto.id === idProducto); 164 | if (!idExiste) { 165 | let producto = new Producto( 166 | idProducto, 167 | nombre, 168 | precioCompra, 169 | precioVenta, 170 | cantidad 171 | ); 172 | 173 | productos.push(producto); 174 | formulario.reset(); 175 | actualizarProductosStorage(); 176 | pintarProductos(); 177 | } else { 178 | alert("El id ya existe"); 179 | } 180 | } else { 181 | alert("Identifíquese antes de agregar un producto"); 182 | } 183 | } 184 | 185 | function eliminarProducto(idProducto) { 186 | let columnaBorrar = document.getElementById(`columna-${idProducto}`); 187 | let indiceBorrar = productos.findIndex( 188 | (producto) => Number(producto.id) === Number(idProducto) 189 | ); 190 | 191 | productos.splice(indiceBorrar, 1); 192 | columnaBorrar.remove(); 193 | actualizarProductosStorage(); 194 | } 195 | 196 | function pintarProductos() { 197 | contenedorProductos.innerHTML = ""; 198 | productos.forEach((producto) => { 199 | let column = document.createElement("div"); 200 | column.className = "col-md-4 mt-3"; 201 | column.id = `columna-${producto.id}`; 202 | column.innerHTML = ` 203 |
204 |
205 |

ID: 206 | ${producto.id} 207 |

208 |

Nombre: 209 | ${producto.nombre} 210 |

211 |

Precio compra: 212 | ${producto.precioCompra} 213 |

214 |

Precio venta: 215 | ${producto.precioVenta} 216 |

217 |

Cantidad: 218 | ${producto.cantidad} 219 |

220 |
221 | 224 |
`; 225 | 226 | contenedorProductos.append(column); 227 | 228 | let botonEliminar = document.getElementById(`botonEliminar-${producto.id}`); 229 | botonEliminar.onclick = () => eliminarProducto(producto.id); 230 | }); 231 | } 232 | 233 | function actualizarProductosStorage() { 234 | let productosJSON = JSON.stringify(productos); 235 | localStorage.setItem("productos", productosJSON); 236 | } 237 | 238 | function actualizarUsuarioStorage() { 239 | localStorage.setItem("usuario", usuario); 240 | } 241 | 242 | function obtenerProductosStorage() { 243 | let productosJSON = localStorage.getItem("productos"); 244 | if (productosJSON) { 245 | productos = JSON.parse(productosJSON); 246 | pintarProductos(); 247 | } 248 | } 249 | 250 | function obtenerUsuarioStorage() { 251 | let usuarioAlmacenado = localStorage.getItem("usuario"); 252 | if (usuarioAlmacenado) { 253 | usuario = usuarioAlmacenado; 254 | mostrarTextoUsuario(); 255 | } 256 | } 257 | 258 | function main() { 259 | inicializarElementos(); 260 | inicializarEventos(); 261 | obtenerProductosStorage(); 262 | obtenerUsuarioStorage(); 263 | } 264 | 265 | main(); 266 | -------------------------------------------------------------------------------- /Clase 12 (Operadores avanzados)/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /Clase 12 (Operadores avanzados)/index.js: -------------------------------------------------------------------------------- 1 | //================ OPERADOR ++ ================ 2 | 3 | //let num = 10; 4 | //num = num + 1; 5 | //num += 1; 6 | 7 | //num++; 8 | 9 | //console.log("El numero es: " + num); 10 | 11 | //================ OPERADOR TERNARIO ================ 12 | 13 | // Utilizando un if else tradicional 14 | 15 | // let permiso; 16 | // let edad = parseInt(prompt("Ingresa tu edad")); 17 | 18 | // if (edad >= 18) { 19 | // permiso = true; 20 | // } else { 21 | // permiso = false; 22 | // } 23 | 24 | // if (permiso) { 25 | // alert("Puede comprar cerveza"); 26 | // } else { 27 | // alert("No puede comprar"); 28 | // } 29 | 30 | // Utilizando un operador ternario 31 | 32 | // let edad = parseInt(prompt("Ingresa tu edad")); 33 | // const permiso = edad >= 18 ? true : false; 34 | 35 | // permiso ? alert("Puede comprar cerveza") : alert("No puede comprar"); 36 | 37 | //================ OPERADOR AND ================ 38 | 39 | //const carrito = []; 40 | 41 | // Utilizando un if tradicional 42 | 43 | // if (carrito.length === 0) { 44 | // console.log("El carrito está vacío!") 45 | // } 46 | 47 | // Utilizando operador AND 48 | //carrito.length === 0 && alert("El carrito está vacío!"); 49 | 50 | //================ OPERADOR OR ================ 51 | 52 | // const usuario = { 53 | // nombre: "John Doe", 54 | // edad: 14, 55 | // }; 56 | // const usuarioDos = null; 57 | 58 | // console.log(usuario || "El usuario uno no existe"); 59 | 60 | // console.log(usuarioDos || "El usuario dos no existe"); 61 | 62 | // EJEMPLO DOS 63 | 64 | // let carrito; 65 | // let carritoLocalStorage = JSON.parse(localStorage.getItem("carrito")); 66 | 67 | // if (carritoLocalStorage) { 68 | // carrito = carritoLocalStorage; 69 | // } else { 70 | // carrito = []; 71 | // } 72 | 73 | // const carrito = JSON.parse(localStorage.getItem("carrito")) || []; 74 | // console.log(JSON.parse(localStorage.getItem("carrito"))); 75 | // console.log(carrito); 76 | 77 | //================ OPERADOR NULLISH ================ 78 | //================ ================ 79 | 80 | //const usuario = null 81 | //console.log(usuario.cursos || "La propiedad no existe"); 82 | 83 | // const usuario = { 84 | // nombre: "John Doe", 85 | // edad: 22, 86 | // cursos: { 87 | // javascript: "aprobado", 88 | // }, 89 | // }; 90 | 91 | // console.log(usuario?.cursos?.javascript || "La propiedad no existe"); 92 | // console.log(usuario?.trabajos?.coderhouse || "La propiedad no existe"); 93 | 94 | //================ DESESTRUCTURACIÓN ================ 95 | 96 | // const usuario = { 97 | // nombre: "John Doe", 98 | // edad: 32, 99 | // telefono: { 100 | // cel: 113334444, 101 | // casa: 5544221345, 102 | // trabajo: 113325555, 103 | // }, 104 | // }; 105 | 106 | // // let nombre = usuario.nombre; 107 | // // let edad = usuario.edad; 108 | 109 | // const { 110 | // nombre, 111 | // edad, 112 | // direccion, 113 | // telefono: { trabajo, casa: telefonoCasa }, 114 | // } = usuario; 115 | 116 | // console.log("Nombre: " + nombre); 117 | // console.log("Edad: " + edad); 118 | // console.log("Dirección: " + direccion); 119 | // console.log("Teléfono trabajo: " + trabajo); 120 | // console.log("Teléfono casa: " + telefonoCasa); 121 | 122 | //================ DESESTRUCTURACIÓN EN PARÁMETROS ================ 123 | 124 | // const usuario = { 125 | // id: 1, 126 | // nombre: "John Doe", 127 | // edad: 32, 128 | // telefono: { 129 | // cel: 113334444, 130 | // casa: 5544221345, 131 | // trabajo: 113325555, 132 | // }, 133 | // }; 134 | 135 | // const imprimirIdNombre = ({ id, nombre }) => { 136 | // console.log("ID: " + id); 137 | // console.log("Nombre: " + nombre); 138 | // }; 139 | 140 | // imprimirIdNombre(usuario); 141 | 142 | //================ DESESTRUCTURACIÓN DE ARRAYS ================ 143 | 144 | // const nombres = ["Juan", "Julieta", "Carlos", "Mariela"]; 145 | 146 | // // omito las dos primeras posiciones 147 | // const [uno, dos] = nombres; 148 | 149 | // console.log(uno); 150 | // console.log(dos); 151 | 152 | // const [, , tres, cuatro] = nombres; 153 | 154 | // console.log(tres); 155 | // console.log(cuatro); 156 | 157 | // const nombresUno = ["Juan", "Julieta"]; 158 | // const nombresDos = ["Carlos", "Mariela"]; 159 | 160 | //================ SPREAD DE ARRAYS ================ 161 | 162 | // const nombres = [...nombresUno, ...nombresDos]; 163 | 164 | // const usuario = { 165 | // nombre: "Jesus", 166 | // edad: 25, 167 | // }; 168 | 169 | //================ SPREAD DE OBJETOS ================ 170 | 171 | // const informacionUsuario = { 172 | // edad: "25.6", 173 | // pais: "CDMX", 174 | // profesion: "Desarrollador", 175 | // telefono: 5522334542, 176 | // }; 177 | 178 | // const usuarioCompleto = { 179 | // ...usuario, 180 | // ...informacionUsuario, 181 | // }; 182 | 183 | // console.log(usuarioCompleto); 184 | 185 | // const productos = [ 186 | // { nombre: "Cuaderno", precio: 15 }, 187 | // { nombre: "Libro de js", precio: 50 }, 188 | // { nombre: "Pluma", precio: 7 }, 189 | // { nombre: "Borrador", precio: 5 }, 190 | // { nombre: "Diccionario", precio: 100 }, 191 | // ]; 192 | 193 | // 194 | // const productosConPrecioActualizado = productos.map((producto) => ({ 195 | // nombre: producto.nombre, 196 | // precio: producto.precio * 1.1, 197 | // })); 198 | // 199 | 200 | // const productosConPrecioActualizado = productos.map((producto) => ({ 201 | // ...producto, 202 | // precio: producto.precio * 1.1, 203 | // })); 204 | 205 | // console.log(productosConPrecioActualizado); 206 | 207 | //================ REST ================ 208 | 209 | function sumar(...numeros) { 210 | console.log("LOS PARÁMETROS RECIBIDOS SON: "); 211 | console.log(numeros); 212 | 213 | let sumatoria = numeros.reduce((acumulador, valor) => acumulador + valor, 0); 214 | return sumatoria; 215 | } 216 | 217 | console.log(sumar(4, 2)); 218 | console.log(sumar(10, 15, 30, 5)); 219 | console.log(sumar(100, 300, 50)); 220 | -------------------------------------------------------------------------------- /Clase 13 (Librerías)/ejemplo_base/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 14 | 15 | 16 |
17 |
18 |
19 | 22 | 25 |
26 |
27 | 30 |
31 |

Identificate

32 |
33 |
34 |
35 |
36 | 37 | 43 |
44 |
45 |
46 | 49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 | 63 | 138 | 143 | 144 | 145 | 146 | -------------------------------------------------------------------------------- /Clase 13 (Librerías)/ejemplo_base/index.js: -------------------------------------------------------------------------------- 1 | //================ EJEMPLO COMPLETO ================ 2 | 3 | // Variables de información 4 | let productos = []; 5 | let usuario; 6 | 7 | // Variables para elementos de autenticación y usuario 8 | 9 | let formularioIdentificacion; 10 | let contenedorIdentificacion; 11 | let contenedorUsuario; 12 | let textoUsuario; 13 | let botonLimpiarStorage; 14 | 15 | // Variables para formulario de productos 16 | let modalAddProduct; 17 | let botonAgregarProducto; 18 | let formulario; 19 | let inputId; 20 | let inputNombre; 21 | let inputPrecioCompra; 22 | let inputPrecioVenta; 23 | let inputCantidad; 24 | let contenedorProductos; 25 | let botonesCerrarModalAgregarProducto; 26 | let modal 27 | 28 | class Producto { 29 | constructor(id, nombre, precioCompra, precioVenta, cantidad) { 30 | this.id = id; 31 | this.nombre = nombre.toUpperCase(); 32 | this.precioCompra = precioCompra; 33 | this.precioVenta = precioVenta; 34 | this.cantidad = cantidad; 35 | } 36 | } 37 | 38 | function inicializarElementos() { 39 | formularioIdentificacion = document.getElementById( 40 | "formularioIdentificacion" 41 | ); 42 | inputUsuario = document.getElementById("inputUsuario"); 43 | contenedorIdentificacion = document.getElementById( 44 | "contenedorIdentificacion" 45 | ); 46 | contenedorUsuario = document.getElementById("contenedorUsuario"); 47 | textoUsuario = document.getElementById("textoUsuario"); 48 | 49 | botonLimpiarStorage = document.getElementById("limpiarStorage"); 50 | formulario = document.getElementById("formularioAgregarProducto"); 51 | inputId = document.getElementById("inputId"); 52 | inputNombre = document.getElementById("inputNombreProducto"); 53 | inputPrecioCompra = document.getElementById("inputPrecioCompra"); 54 | inputPrecioVenta = document.getElementById("inputPrecioVenta"); 55 | inputCantidad = document.getElementById("inputCantidad"); 56 | contenedorProductos = document.getElementById("contenedorProductos"); 57 | 58 | botonesCerrarModalAgregarProducto = document.getElementsByClassName( 59 | "btnCerrarModalAgregarProducto" 60 | ); 61 | modalAddProduct = document.getElementById("modalAddProduct"); 62 | botonAgregarProducto = document.getElementById("btnAgregarProducto"); 63 | modal = new bootstrap.Modal(modalAddProduct); 64 | } 65 | 66 | function inicializarEventos() { 67 | formulario.onsubmit = (event) => validarFormulario(event); 68 | formularioIdentificacion.onsubmit = (event) => identificarUsuario(event); 69 | botonLimpiarStorage.onclick = eliminarStorage; 70 | botonAgregarProducto.onclick = abrirModalAgregarProducto; 71 | 72 | for (const boton of botonesCerrarModalAgregarProducto) { 73 | boton.onclick = cerrarModalAgregarProducto; 74 | } 75 | } 76 | 77 | function abrirModalAgregarProducto() { 78 | if (usuario) { 79 | modal.show(); 80 | } else { 81 | alert("Identifíquese antes de agregar un producto"); 82 | } 83 | } 84 | 85 | function cerrarModalAgregarProducto() { 86 | formulario.reset(); 87 | modal.hide(); 88 | } 89 | 90 | function eliminarStorage() { 91 | localStorage.clear(); 92 | usuario = ""; 93 | productos = []; 94 | mostrarFormularioIdentificacion(); 95 | pintarProductos(); 96 | } 97 | 98 | function identificarUsuario(event) { 99 | event.preventDefault(); 100 | usuario = inputUsuario.value; 101 | formularioIdentificacion.reset(); 102 | actualizarUsuarioStorage(); 103 | mostrarTextoUsuario(); 104 | } 105 | 106 | function mostrarTextoUsuario() { 107 | contenedorIdentificacion.hidden = true; 108 | contenedorUsuario.hidden = false; 109 | textoUsuario.innerHTML += ` ${usuario}`; 110 | } 111 | 112 | function mostrarFormularioIdentificacion() { 113 | contenedorIdentificacion.hidden = false; 114 | contenedorUsuario.hidden = true; 115 | textoUsuario.innerHTML = ``; 116 | } 117 | 118 | function validarFormulario(event) { 119 | event.preventDefault(); 120 | let idProducto = inputId.value; 121 | let nombre = inputNombre.value; 122 | let precioCompra = parseFloat(inputPrecioCompra.value); 123 | let precioVenta = parseFloat(inputPrecioVenta.value); 124 | let cantidad = parseInt(inputCantidad.value); 125 | 126 | const idExiste = productos.some((producto) => producto.id === idProducto); 127 | if (!idExiste) { 128 | let producto = new Producto( 129 | idProducto, 130 | nombre, 131 | precioCompra, 132 | precioVenta, 133 | cantidad 134 | ); 135 | 136 | productos.push(producto); 137 | formulario.reset(); 138 | alert("Producto agregado exitosamente"); 139 | actualizarProductosStorage(); 140 | pintarProductos(); 141 | } else { 142 | alert("El id ya existe"); 143 | } 144 | } 145 | 146 | function eliminarProducto(idProducto) { 147 | let columnaBorrar = document.getElementById(`columna-${idProducto}`); 148 | let indiceBorrar = productos.findIndex( 149 | (producto) => Number(producto.id) === Number(idProducto) 150 | ); 151 | 152 | productos.splice(indiceBorrar, 1); 153 | columnaBorrar.remove(); 154 | actualizarProductosStorage(); 155 | } 156 | 157 | function pintarProductos() { 158 | contenedorProductos.innerHTML = ""; 159 | productos.forEach((producto) => { 160 | let column = document.createElement("div"); 161 | column.className = "col-md-4 mt-3"; 162 | column.id = `columna-${producto.id}`; 163 | column.innerHTML = ` 164 |
165 |
166 |

ID: 167 | ${producto.id} 168 |

169 |

Nombre: 170 | ${producto.nombre} 171 |

172 |

Precio compra: 173 | ${producto.precioCompra} 174 |

175 |

Precio venta: 176 | ${producto.precioVenta} 177 |

178 |

Cantidad: 179 | ${producto.cantidad} 180 |

181 |
182 | 185 |
`; 186 | 187 | contenedorProductos.append(column); 188 | 189 | let botonEliminar = document.getElementById(`botonEliminar-${producto.id}`); 190 | botonEliminar.onclick = () => eliminarProducto(producto.id); 191 | }); 192 | } 193 | 194 | function actualizarProductosStorage() { 195 | let productosJSON = JSON.stringify(productos); 196 | localStorage.setItem("productos", productosJSON); 197 | } 198 | 199 | function actualizarUsuarioStorage() { 200 | localStorage.setItem("usuario", usuario); 201 | } 202 | 203 | function obtenerProductosStorage() { 204 | let productosJSON = localStorage.getItem("productos"); 205 | if (productosJSON) { 206 | productos = JSON.parse(productosJSON); 207 | pintarProductos(); 208 | } 209 | } 210 | 211 | function obtenerUsuarioStorage() { 212 | let usuarioAlmacenado = localStorage.getItem("usuario"); 213 | if (usuarioAlmacenado) { 214 | usuario = usuarioAlmacenado; 215 | mostrarTextoUsuario(); 216 | } 217 | } 218 | 219 | function main() { 220 | inicializarElementos(); 221 | inicializarEventos(); 222 | obtenerProductosStorage(); 223 | obtenerUsuarioStorage(); 224 | } 225 | 226 | main(); 227 | -------------------------------------------------------------------------------- /Clase 13 (Librerías)/ejemplo_completo/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 14 | 15 | 16 | 17 | 18 |
19 |
20 |
21 | 24 | 27 |
28 |
29 | 32 |
33 |

Identificate

34 |
35 |
36 |
37 |
38 | 39 | 45 |
46 |
47 |
48 | 51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 | 65 | 140 | 145 | 146 | 147 | 148 | 149 | 150 | -------------------------------------------------------------------------------- /Clase 13 (Librerías)/ejemplo_completo/index.js: -------------------------------------------------------------------------------- 1 | //================ EJEMPLO COMPLETO ================ 2 | 3 | // Variables de información 4 | let productos = []; 5 | let usuario; 6 | 7 | // Variables para elementos de autenticación y usuario 8 | 9 | let formularioIdentificacion; 10 | let contenedorIdentificacion; 11 | let contenedorUsuario; 12 | let textoUsuario; 13 | let botonLimpiarStorage; 14 | 15 | // Variables para formulario de productos 16 | let modalAddProduct; 17 | let botonAgregarProducto; 18 | let formulario; 19 | let inputId; 20 | let inputNombre; 21 | let inputPrecioCompra; 22 | let inputPrecioVenta; 23 | let inputCantidad; 24 | let contenedorProductos; 25 | let botonesCerrarModalAgregarProducto; 26 | let modal; 27 | 28 | class Producto { 29 | constructor(id, nombre, precioCompra, precioVenta, cantidad) { 30 | this.id = id; 31 | this.nombre = nombre.toUpperCase(); 32 | this.precioCompra = precioCompra; 33 | this.precioVenta = precioVenta; 34 | this.cantidad = cantidad; 35 | } 36 | } 37 | 38 | function inicializarElementos() { 39 | formularioIdentificacion = document.getElementById( 40 | "formularioIdentificacion" 41 | ); 42 | inputUsuario = document.getElementById("inputUsuario"); 43 | contenedorIdentificacion = document.getElementById( 44 | "contenedorIdentificacion" 45 | ); 46 | contenedorUsuario = document.getElementById("contenedorUsuario"); 47 | textoUsuario = document.getElementById("textoUsuario"); 48 | 49 | botonLimpiarStorage = document.getElementById("limpiarStorage"); 50 | formulario = document.getElementById("formularioAgregarProducto"); 51 | inputId = document.getElementById("inputId"); 52 | inputNombre = document.getElementById("inputNombreProducto"); 53 | inputPrecioCompra = document.getElementById("inputPrecioCompra"); 54 | inputPrecioVenta = document.getElementById("inputPrecioVenta"); 55 | inputCantidad = document.getElementById("inputCantidad"); 56 | contenedorProductos = document.getElementById("contenedorProductos"); 57 | 58 | botonesCerrarModalAgregarProducto = document.getElementsByClassName( 59 | "btnCerrarModalAgregarProducto" 60 | ); 61 | modalAddProduct = document.getElementById("modalAddProduct"); 62 | botonAgregarProducto = document.getElementById("btnAgregarProducto"); 63 | modal = new bootstrap.Modal(modalAddProduct); 64 | } 65 | 66 | function inicializarEventos() { 67 | formulario.onsubmit = (event) => validarFormulario(event); 68 | formularioIdentificacion.onsubmit = (event) => identificarUsuario(event); 69 | botonLimpiarStorage.onclick = eliminarStorage; 70 | botonAgregarProducto.onclick = abrirModalAgregarProducto; 71 | 72 | for (const boton of botonesCerrarModalAgregarProducto) { 73 | boton.onclick = cerrarModalAgregarProducto; 74 | } 75 | } 76 | 77 | function abrirModalAgregarProducto() { 78 | if (usuario) { 79 | modal.show(); 80 | } else { 81 | alert("Identifíquese antes de agregar un producto"); 82 | } 83 | } 84 | 85 | function cerrarModalAgregarProducto() { 86 | formulario.reset(); 87 | modal.hide(); 88 | } 89 | 90 | function eliminarStorage() { 91 | localStorage.clear(); 92 | usuario = ""; 93 | productos = []; 94 | mostrarFormularioIdentificacion(); 95 | pintarProductos(); 96 | } 97 | 98 | function identificarUsuario(event) { 99 | event.preventDefault(); 100 | usuario = inputUsuario.value; 101 | formularioIdentificacion.reset(); 102 | actualizarUsuarioStorage(); 103 | mostrarTextoUsuario(); 104 | } 105 | 106 | function mostrarTextoUsuario() { 107 | contenedorIdentificacion.hidden = true; 108 | contenedorUsuario.hidden = false; 109 | textoUsuario.innerHTML += ` ${usuario}`; 110 | } 111 | 112 | function mostrarFormularioIdentificacion() { 113 | contenedorIdentificacion.hidden = false; 114 | contenedorUsuario.hidden = true; 115 | textoUsuario.innerHTML = ``; 116 | } 117 | 118 | function validarFormulario(event) { 119 | event.preventDefault(); 120 | let idProducto = inputId.value; 121 | let nombre = inputNombre.value; 122 | let precioCompra = parseFloat(inputPrecioCompra.value); 123 | let precioVenta = parseFloat(inputPrecioVenta.value); 124 | let cantidad = parseInt(inputCantidad.value); 125 | 126 | const idExiste = productos.some((producto) => producto.id === idProducto); 127 | if (!idExiste) { 128 | let producto = new Producto( 129 | idProducto, 130 | nombre, 131 | precioCompra, 132 | precioVenta, 133 | cantidad 134 | ); 135 | 136 | productos.push(producto); 137 | formulario.reset(); 138 | actualizarProductosStorage(); 139 | pintarProductos(); 140 | mostrarMensajeConfirmacion( 141 | `El producto ${nombre} fue agregado exitosamente`, 142 | "info" 143 | ); 144 | } else { 145 | alert("El id ya existe"); 146 | } 147 | } 148 | 149 | function confirmarEliminacion(idProducto) { 150 | Swal.fire({ 151 | icon: "question", 152 | title: "¿Estas seguro que quieres eliminar el producto?", 153 | showCancelButton: true, 154 | confirmButtonText: "Eliminar", 155 | cancelButtonText: "Cancelar", 156 | }).then((result) => { 157 | if (result.isConfirmed) { 158 | eliminarProducto(idProducto); 159 | } 160 | }); 161 | } 162 | 163 | function eliminarProducto(idProducto) { 164 | let columnaBorrar = document.getElementById(`columna-${idProducto}`); 165 | let indiceBorrar = productos.findIndex( 166 | (producto) => Number(producto.id) === Number(idProducto) 167 | ); 168 | 169 | let nombreProductoEliminado = productos[indiceBorrar].nombre; 170 | productos.splice(indiceBorrar, 1); 171 | columnaBorrar.remove(); 172 | actualizarProductosStorage(); 173 | mostrarMensajeConfirmacion( 174 | `El producto ${nombreProductoEliminado} fue eliminado exitosamente`, 175 | "danger" 176 | ); 177 | } 178 | 179 | function pintarProductos() { 180 | contenedorProductos.innerHTML = ""; 181 | productos.forEach((producto) => { 182 | let column = document.createElement("div"); 183 | column.className = "col-md-4 mt-3"; 184 | column.id = `columna-${producto.id}`; 185 | column.innerHTML = ` 186 |
187 |
188 |

ID: 189 | ${producto.id} 190 |

191 |

Nombre: 192 | ${producto.nombre} 193 |

194 |

Precio compra: 195 | ${producto.precioCompra} 196 |

197 |

Precio venta: 198 | ${producto.precioVenta} 199 |

200 |

Cantidad: 201 | ${producto.cantidad} 202 |

203 |
204 | 207 |
`; 208 | 209 | contenedorProductos.append(column); 210 | 211 | let botonEliminar = document.getElementById(`botonEliminar-${producto.id}`); 212 | botonEliminar.onclick = () => confirmarEliminacion(producto.id); 213 | }); 214 | } 215 | 216 | function actualizarProductosStorage() { 217 | let productosJSON = JSON.stringify(productos); 218 | localStorage.setItem("productos", productosJSON); 219 | } 220 | 221 | function actualizarUsuarioStorage() { 222 | localStorage.setItem("usuario", usuario); 223 | } 224 | 225 | function obtenerProductosStorage() { 226 | let productosJSON = localStorage.getItem("productos"); 227 | if (productosJSON) { 228 | productos = JSON.parse(productosJSON); 229 | pintarProductos(); 230 | } 231 | } 232 | 233 | function obtenerUsuarioStorage() { 234 | let usuarioAlmacenado = localStorage.getItem("usuario"); 235 | if (usuarioAlmacenado) { 236 | usuario = usuarioAlmacenado; 237 | mostrarTextoUsuario(); 238 | } 239 | } 240 | 241 | function mostrarMensajeConfirmacion(mensaje, clase) { 242 | Toastify({ 243 | text: mensaje, 244 | duration: 30000, 245 | close: true, 246 | gravity: "top", 247 | position: "right", 248 | className: clase 249 | }).showToast(); 250 | } 251 | 252 | function main() { 253 | inicializarElementos(); 254 | inicializarEventos(); 255 | obtenerProductosStorage(); 256 | obtenerUsuarioStorage(); 257 | } 258 | 259 | main(); 260 | -------------------------------------------------------------------------------- /Clase 13 (Librerías)/ejemplo_completo/style.css: -------------------------------------------------------------------------------- 1 | .info{ 2 | background: blueviolet; 3 | } -------------------------------------------------------------------------------- /Clase 13 (Librerías)/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 14 | 15 | 16 | 17 |
18 | 19 |
20 | 21 |
22 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /Clase 13 (Librerías)/index.js: -------------------------------------------------------------------------------- 1 | const botonSwal = document.getElementById("btnMostrarSwal"); 2 | 3 | botonSwal.onclick = mostrarSwal; 4 | 5 | function mostrarSwal() { 6 | Swal.fire({ 7 | icon: "success", 8 | title: "Mensaje mostrado", 9 | }); 10 | } 11 | 12 | const botonToast = document.getElementById("btnMostrarToast"); 13 | 14 | botonToast.onclick = mostrarToast; 15 | function mostrarToast() { 16 | Toastify({ 17 | text: "Mostrar toast", 18 | duration: 3000, 19 | close: true, 20 | }).showToast(); 21 | } 22 | -------------------------------------------------------------------------------- /Clase 14 (Async y promesas)/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 14 | 15 | 16 |
17 |
18 |
19 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /Clase 14 (Async y promesas)/index.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | //================ EJEMPLO PROCESO ASÍNCRONO ================ 4 | 5 | // setTimeout(() => { 6 | // console.log("Proceso asincrónico"); 7 | // }, 3000); 8 | 9 | //================ EJEMPLO DE EJECUCIÓN SINCRONA Y ASÍNCRONA ================ 10 | 11 | // console.log("Inicia proceso"); 12 | 13 | // setTimeout(() => { 14 | // console.log("Mitad de proceso"); 15 | // }, 2000); 16 | 17 | // console.log("Fin proceso"); 18 | //================ EJEMPLO DE INTERVAL ================ 19 | 20 | 21 | //================ EJEMPLO DE INTERVAL Y CLEAR INTERVAL ================ 22 | 23 | // let counter = 0; 24 | 25 | // const interval = setInterval(() => { 26 | // counter++; 27 | // console.log("Counter: ", counter); 28 | 29 | // if (counter >= 5) { 30 | // clearInterval(interval); 31 | // console.log("Se removió el intervalo"); 32 | // } 33 | // }, 1000); 34 | 35 | //================ EJEMPLO DE SIMULACIÓN DE CONSULTA A UN API ================ 36 | 37 | let contenedor = document.getElementById("contenedor-productos"); 38 | 39 | const BD = [ 40 | { id: 1, nombre: "Producto 1", precio: 1500 }, 41 | { id: 2, nombre: "Producto 2", precio: 2500 }, 42 | { id: 3, nombre: "Producto 3", precio: 3500 }, 43 | { id: 4, nombre: "Producto 4", precio: 3500 }, 44 | ]; 45 | 46 | const pedirProductos = () => { 47 | return new Promise((resolve, reject) => { 48 | setTimeout(() => { 49 | resolve(BD); 50 | }, 3000); 51 | }); 52 | }; 53 | 54 | const pintarProductos = () => { 55 | productos.forEach((producto) => { 56 | const column = document.createElement("div"); 57 | column.className = "col-md-3"; 58 | column.innerHTML = `
59 |

${producto.id}

60 |

${producto.nombre}

61 |

${producto.precio}

62 |
`; 63 | contenedor.appendChild(column); 64 | }); 65 | }; 66 | 67 | let productos = []; 68 | 69 | pedirProductos() 70 | .then((response) => { 71 | productos = [...response]; 72 | console.log(response); 73 | pintarProductos(); 74 | }) 75 | .catch((error) => { 76 | console.error(error); 77 | }) 78 | .finally(() => { 79 | console.log("Esto se ejecuta al final"); 80 | }); -------------------------------------------------------------------------------- /Clase 15 (AJAX y Fetch)/ejemplo_base/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 14 | 15 | 16 | 17 | 18 |
19 |
20 |
21 | 24 | 27 |
28 |
29 | 32 |
33 |

Identificate

34 |
35 |
36 |
37 |
38 | 39 | 45 |
46 |
47 |
48 | 51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 | 65 | 140 | 145 | 146 | 147 | 148 | 149 | 150 | -------------------------------------------------------------------------------- /Clase 15 (AJAX y Fetch)/ejemplo_base/index.js: -------------------------------------------------------------------------------- 1 | //================ EJEMPLO COMPLETO ================ 2 | 3 | // Variables de información 4 | let productos = []; 5 | let usuario; 6 | 7 | // Variables para elementos de autenticación y usuario 8 | 9 | let formularioIdentificacion; 10 | let contenedorIdentificacion; 11 | let contenedorUsuario; 12 | let textoUsuario; 13 | let botonLimpiarStorage; 14 | 15 | // Variables para formulario de productos 16 | let modalAddProduct; 17 | let botonAgregarProducto; 18 | let formulario; 19 | let inputId; 20 | let inputNombre; 21 | let inputPrecioCompra; 22 | let inputPrecioVenta; 23 | let inputCantidad; 24 | let contenedorProductos; 25 | let botonesCerrarModalAgregarProducto; 26 | let modal; 27 | 28 | class Producto { 29 | constructor(id, nombre, precioCompra, precioVenta, cantidad) { 30 | this.id = id; 31 | this.nombre = nombre.toUpperCase(); 32 | this.precioCompra = precioCompra; 33 | this.precioVenta = precioVenta; 34 | this.cantidad = cantidad; 35 | } 36 | } 37 | 38 | function inicializarElementos() { 39 | formularioIdentificacion = document.getElementById( 40 | "formularioIdentificacion" 41 | ); 42 | inputUsuario = document.getElementById("inputUsuario"); 43 | contenedorIdentificacion = document.getElementById( 44 | "contenedorIdentificacion" 45 | ); 46 | contenedorUsuario = document.getElementById("contenedorUsuario"); 47 | textoUsuario = document.getElementById("textoUsuario"); 48 | 49 | botonLimpiarStorage = document.getElementById("limpiarStorage"); 50 | formulario = document.getElementById("formularioAgregarProducto"); 51 | inputId = document.getElementById("inputId"); 52 | inputNombre = document.getElementById("inputNombreProducto"); 53 | inputPrecioCompra = document.getElementById("inputPrecioCompra"); 54 | inputPrecioVenta = document.getElementById("inputPrecioVenta"); 55 | inputCantidad = document.getElementById("inputCantidad"); 56 | contenedorProductos = document.getElementById("contenedorProductos"); 57 | 58 | botonesCerrarModalAgregarProducto = document.getElementsByClassName( 59 | "btnCerrarModalAgregarProducto" 60 | ); 61 | modalAddProduct = document.getElementById("modalAddProduct"); 62 | botonAgregarProducto = document.getElementById("btnAgregarProducto"); 63 | modal = new bootstrap.Modal(modalAddProduct); 64 | } 65 | 66 | function inicializarEventos() { 67 | formulario.onsubmit = (event) => validarFormulario(event); 68 | formularioIdentificacion.onsubmit = (event) => identificarUsuario(event); 69 | botonLimpiarStorage.onclick = eliminarStorage; 70 | botonAgregarProducto.onclick = abrirModalAgregarProducto; 71 | 72 | for (const boton of botonesCerrarModalAgregarProducto) { 73 | boton.onclick = cerrarModalAgregarProducto; 74 | } 75 | } 76 | 77 | function abrirModalAgregarProducto() { 78 | if (usuario) { 79 | modal.show(); 80 | } else { 81 | alert("Identifíquese antes de agregar un producto"); 82 | } 83 | } 84 | 85 | function cerrarModalAgregarProducto() { 86 | formulario.reset(); 87 | modal.hide(); 88 | } 89 | 90 | function eliminarStorage() { 91 | localStorage.clear(); 92 | usuario = ""; 93 | productos = []; 94 | mostrarFormularioIdentificacion(); 95 | pintarProductos(); 96 | } 97 | 98 | function identificarUsuario(event) { 99 | event.preventDefault(); 100 | usuario = inputUsuario.value; 101 | formularioIdentificacion.reset(); 102 | actualizarUsuarioStorage(); 103 | mostrarTextoUsuario(); 104 | } 105 | 106 | function mostrarTextoUsuario() { 107 | contenedorIdentificacion.hidden = true; 108 | contenedorUsuario.hidden = false; 109 | textoUsuario.innerHTML += ` ${usuario}`; 110 | } 111 | 112 | function mostrarFormularioIdentificacion() { 113 | contenedorIdentificacion.hidden = false; 114 | contenedorUsuario.hidden = true; 115 | textoUsuario.innerHTML = ``; 116 | } 117 | 118 | function validarFormulario(event) { 119 | event.preventDefault(); 120 | let idProducto = inputId.value; 121 | let nombre = inputNombre.value; 122 | let precioCompra = parseFloat(inputPrecioCompra.value); 123 | let precioVenta = parseFloat(inputPrecioVenta.value); 124 | let cantidad = parseInt(inputCantidad.value); 125 | 126 | const idExiste = productos.some((producto) => producto.id === idProducto); 127 | if (!idExiste) { 128 | let producto = new Producto( 129 | idProducto, 130 | nombre, 131 | precioCompra, 132 | precioVenta, 133 | cantidad 134 | ); 135 | 136 | productos.push(producto); 137 | formulario.reset(); 138 | actualizarProductosStorage(); 139 | pintarProductos(); 140 | mostrarMensajeConfirmacion( 141 | `El producto ${nombre} fue agregado exitosamente`, 142 | "info" 143 | ); 144 | } else { 145 | alert("El id ya existe"); 146 | } 147 | } 148 | 149 | function confirmarEliminacion(idProducto) { 150 | Swal.fire({ 151 | icon: "question", 152 | title: "¿Estas seguro que quieres eliminar el producto?", 153 | showCancelButton: true, 154 | confirmButtonText: "Eliminar", 155 | cancelButtonText: "Cancelar", 156 | }).then((result) => { 157 | if (result.isConfirmed) { 158 | eliminarProducto(idProducto); 159 | } 160 | }); 161 | } 162 | 163 | function eliminarProducto(idProducto) { 164 | let columnaBorrar = document.getElementById(`columna-${idProducto}`); 165 | let indiceBorrar = productos.findIndex( 166 | (producto) => Number(producto.id) === Number(idProducto) 167 | ); 168 | 169 | let nombreProductoEliminado = productos[indiceBorrar].nombre; 170 | productos.splice(indiceBorrar, 1); 171 | columnaBorrar.remove(); 172 | actualizarProductosStorage(); 173 | mostrarMensajeConfirmacion( 174 | `El producto ${nombreProductoEliminado} fue eliminado exitosamente`, 175 | "danger" 176 | ); 177 | } 178 | 179 | function pintarProductos() { 180 | contenedorProductos.innerHTML = ""; 181 | productos.forEach((producto) => { 182 | let column = document.createElement("div"); 183 | column.className = "col-md-4 mt-3"; 184 | column.id = `columna-${producto.id}`; 185 | column.innerHTML = ` 186 |
187 |
188 |

ID: 189 | ${producto.id} 190 |

191 |

Nombre: 192 | ${producto.nombre} 193 |

194 |

Precio compra: 195 | ${producto.precioCompra} 196 |

197 |

Precio venta: 198 | ${producto.precioVenta} 199 |

200 |

Cantidad: 201 | ${producto.cantidad} 202 |

203 |
204 | 207 |
`; 208 | 209 | contenedorProductos.append(column); 210 | 211 | let botonEliminar = document.getElementById(`botonEliminar-${producto.id}`); 212 | botonEliminar.onclick = () => confirmarEliminacion(producto.id); 213 | }); 214 | } 215 | 216 | function actualizarProductosStorage() { 217 | let productosJSON = JSON.stringify(productos); 218 | localStorage.setItem("productos", productosJSON); 219 | } 220 | 221 | function actualizarUsuarioStorage() { 222 | localStorage.setItem("usuario", usuario); 223 | } 224 | 225 | function obtenerProductosStorage() { 226 | let productosJSON = localStorage.getItem("productos"); 227 | if (productosJSON) { 228 | productos = JSON.parse(productosJSON); 229 | pintarProductos(); 230 | } 231 | } 232 | 233 | function obtenerUsuarioStorage() { 234 | let usuarioAlmacenado = localStorage.getItem("usuario"); 235 | if (usuarioAlmacenado) { 236 | usuario = usuarioAlmacenado; 237 | mostrarTextoUsuario(); 238 | } 239 | } 240 | 241 | function mostrarMensajeConfirmacion(mensaje, clase) { 242 | Toastify({ 243 | text: mensaje, 244 | duration: 30000, 245 | close: true, 246 | gravity: "top", 247 | position: "right", 248 | className: clase 249 | }).showToast(); 250 | } 251 | 252 | function main() { 253 | inicializarElementos(); 254 | inicializarEventos(); 255 | obtenerProductosStorage(); 256 | obtenerUsuarioStorage(); 257 | } 258 | 259 | main(); 260 | -------------------------------------------------------------------------------- /Clase 15 (AJAX y Fetch)/ejemplo_base/style.css: -------------------------------------------------------------------------------- 1 | .info{ 2 | background: blueviolet; 3 | } -------------------------------------------------------------------------------- /Clase 15 (AJAX y Fetch)/ejemplo_completo/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 14 | 15 | 16 | 17 | 18 |
19 |
20 |
21 | 24 | 27 |
28 |
29 | 32 |
33 |

Identificate

34 |
35 |
36 |
37 |
38 | 39 | 45 |
46 |
47 |
48 | 51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 | 65 | 140 | 145 | 146 | 147 | 148 | 149 | 150 | -------------------------------------------------------------------------------- /Clase 15 (AJAX y Fetch)/ejemplo_completo/index.js: -------------------------------------------------------------------------------- 1 | //================ EJEMPLO COMPLETO ================ 2 | 3 | // Variables de información 4 | let productos = []; 5 | let usuario; 6 | 7 | // Variables para elementos de autenticación y usuario 8 | 9 | let formularioIdentificacion; 10 | let contenedorIdentificacion; 11 | let contenedorUsuario; 12 | let textoUsuario; 13 | let botonLimpiarStorage; 14 | 15 | // Variables para formulario de productos 16 | let modalAddProduct; 17 | let botonAgregarProducto; 18 | let formulario; 19 | let inputId; 20 | let inputNombre; 21 | let inputPrecioCompra; 22 | let inputPrecioVenta; 23 | let inputCantidad; 24 | let contenedorProductos; 25 | let botonesCerrarModalAgregarProducto; 26 | let modal; 27 | 28 | class Producto { 29 | constructor(id, nombre, precioCompra, precioVenta, cantidad) { 30 | this.id = id; 31 | this.nombre = nombre.toUpperCase(); 32 | this.precioCompra = precioCompra; 33 | this.precioVenta = precioVenta; 34 | this.cantidad = cantidad; 35 | } 36 | } 37 | 38 | function inicializarElementos() { 39 | formularioIdentificacion = document.getElementById( 40 | "formularioIdentificacion" 41 | ); 42 | inputUsuario = document.getElementById("inputUsuario"); 43 | contenedorIdentificacion = document.getElementById( 44 | "contenedorIdentificacion" 45 | ); 46 | contenedorUsuario = document.getElementById("contenedorUsuario"); 47 | textoUsuario = document.getElementById("textoUsuario"); 48 | 49 | botonLimpiarStorage = document.getElementById("limpiarStorage"); 50 | formulario = document.getElementById("formularioAgregarProducto"); 51 | inputId = document.getElementById("inputId"); 52 | inputNombre = document.getElementById("inputNombreProducto"); 53 | inputPrecioCompra = document.getElementById("inputPrecioCompra"); 54 | inputPrecioVenta = document.getElementById("inputPrecioVenta"); 55 | inputCantidad = document.getElementById("inputCantidad"); 56 | contenedorProductos = document.getElementById("contenedorProductos"); 57 | 58 | botonesCerrarModalAgregarProducto = document.getElementsByClassName( 59 | "btnCerrarModalAgregarProducto" 60 | ); 61 | modalAddProduct = document.getElementById("modalAddProduct"); 62 | botonAgregarProducto = document.getElementById("btnAgregarProducto"); 63 | modal = new bootstrap.Modal(modalAddProduct); 64 | } 65 | 66 | function inicializarEventos() { 67 | formulario.onsubmit = (event) => validarFormulario(event); 68 | formularioIdentificacion.onsubmit = (event) => identificarUsuario(event); 69 | botonLimpiarStorage.onclick = eliminarStorage; 70 | botonAgregarProducto.onclick = abrirModalAgregarProducto; 71 | 72 | for (const boton of botonesCerrarModalAgregarProducto) { 73 | boton.onclick = cerrarModalAgregarProducto; 74 | } 75 | } 76 | 77 | function abrirModalAgregarProducto() { 78 | if (usuario) { 79 | modal.show(); 80 | } else { 81 | alert("Identifíquese antes de agregar un producto"); 82 | } 83 | } 84 | 85 | function cerrarModalAgregarProducto() { 86 | formulario.reset(); 87 | modal.hide(); 88 | } 89 | 90 | function eliminarStorage() { 91 | localStorage.clear(); 92 | usuario = ""; 93 | productos = []; 94 | mostrarFormularioIdentificacion(); 95 | pintarProductos(); 96 | } 97 | 98 | function identificarUsuario(event) { 99 | event.preventDefault(); 100 | usuario = inputUsuario.value; 101 | formularioIdentificacion.reset(); 102 | actualizarUsuarioStorage(); 103 | mostrarTextoUsuario(); 104 | } 105 | 106 | function mostrarTextoUsuario() { 107 | contenedorIdentificacion.hidden = true; 108 | contenedorUsuario.hidden = false; 109 | textoUsuario.innerHTML += ` ${usuario}`; 110 | } 111 | 112 | function mostrarFormularioIdentificacion() { 113 | contenedorIdentificacion.hidden = false; 114 | contenedorUsuario.hidden = true; 115 | textoUsuario.innerHTML = ``; 116 | } 117 | 118 | function validarFormulario(event) { 119 | event.preventDefault(); 120 | let idProducto = inputId.value; 121 | let nombre = inputNombre.value; 122 | let precioCompra = parseFloat(inputPrecioCompra.value); 123 | let precioVenta = parseFloat(inputPrecioVenta.value); 124 | let cantidad = parseInt(inputCantidad.value); 125 | 126 | const idExiste = productos.some((producto) => producto.id === idProducto); 127 | if (!idExiste) { 128 | let producto = new Producto( 129 | idProducto, 130 | nombre, 131 | precioCompra, 132 | precioVenta, 133 | cantidad 134 | ); 135 | 136 | productos.push(producto); 137 | formulario.reset(); 138 | actualizarProductosStorage(); 139 | pintarProductos(); 140 | mostrarMensajeConfirmacion( 141 | `El producto ${nombre} fue agregado exitosamente`, 142 | "info" 143 | ); 144 | } else { 145 | alert("El id ya existe"); 146 | } 147 | } 148 | 149 | function confirmarEliminacion(idProducto) { 150 | Swal.fire({ 151 | icon: "question", 152 | title: "¿Estas seguro que quieres eliminar el producto?", 153 | showCancelButton: true, 154 | confirmButtonText: "Eliminar", 155 | cancelButtonText: "Cancelar", 156 | }).then((result) => { 157 | if (result.isConfirmed) { 158 | eliminarProducto(idProducto); 159 | } 160 | }); 161 | } 162 | 163 | function eliminarProducto(idProducto) { 164 | let columnaBorrar = document.getElementById(`columna-${idProducto}`); 165 | let indiceBorrar = productos.findIndex( 166 | (producto) => Number(producto.id) === Number(idProducto) 167 | ); 168 | 169 | let nombreProductoEliminado = productos[indiceBorrar].nombre; 170 | productos.splice(indiceBorrar, 1); 171 | columnaBorrar.remove(); 172 | actualizarProductosStorage(); 173 | mostrarMensajeConfirmacion( 174 | `El producto ${nombreProductoEliminado} fue eliminado exitosamente`, 175 | "danger" 176 | ); 177 | } 178 | 179 | function pintarProductos() { 180 | contenedorProductos.innerHTML = ""; 181 | productos.forEach((producto) => { 182 | let column = document.createElement("div"); 183 | column.className = "col-md-4 mt-3"; 184 | column.id = `columna-${producto.id}`; 185 | column.innerHTML = ` 186 |
187 |
188 |

ID: 189 | ${producto.id} 190 |

191 |

Nombre: 192 | ${producto.nombre} 193 |

194 |

Precio compra: 195 | ${producto.precioCompra} 196 |

197 |

Precio venta: 198 | ${producto.precioVenta} 199 |

200 |

Cantidad: 201 | ${producto.cantidad} 202 |

203 |
204 | 207 |
`; 208 | 209 | contenedorProductos.append(column); 210 | 211 | let botonEliminar = document.getElementById(`botonEliminar-${producto.id}`); 212 | botonEliminar.onclick = () => confirmarEliminacion(producto.id); 213 | }); 214 | } 215 | 216 | function actualizarProductosStorage() { 217 | let productosJSON = JSON.stringify(productos); 218 | localStorage.setItem("productos", productosJSON); 219 | } 220 | 221 | function actualizarUsuarioStorage() { 222 | localStorage.setItem("usuario", usuario); 223 | } 224 | 225 | function obtenerProductosStorage() { 226 | let productosJSON = localStorage.getItem("productos"); 227 | if (productosJSON) { 228 | productos = JSON.parse(productosJSON); 229 | pintarProductos(); 230 | } 231 | } 232 | 233 | function obtenerUsuarioStorage() { 234 | let usuarioAlmacenado = localStorage.getItem("usuario"); 235 | if (usuarioAlmacenado) { 236 | usuario = usuarioAlmacenado; 237 | mostrarTextoUsuario(); 238 | } 239 | } 240 | 241 | function mostrarMensajeConfirmacion(mensaje, clase) { 242 | Toastify({ 243 | text: mensaje, 244 | duration: 30000, 245 | close: true, 246 | gravity: "top", 247 | position: "right", 248 | className: clase, 249 | }).showToast(); 250 | } 251 | 252 | async function consultarProductosServer() { 253 | // fetch("https://6244e0467701ec8f724a5a7f.mockapi.io/api/productos") 254 | // .then((response) => response.json()) 255 | // .then((data) => console.log(data)) 256 | // .catch((error) => console.log(error)); 257 | 258 | // fetch("./productos.json") 259 | // .then((response) => response.json()) 260 | // .then((data) => { 261 | // productos = [...data] 262 | // pintarProductos(); 263 | // }) 264 | // .catch((error) => console.log(error)); 265 | 266 | try { 267 | const response = await fetch( 268 | "https://6244e0467701ec8f724a5a7f.mockapi.io/api/productos" 269 | ); 270 | const data = await response.json(); 271 | productos = [...data]; 272 | pintarProductos(); 273 | } catch (error) { 274 | console.log(error); 275 | } 276 | } 277 | 278 | function main() { 279 | inicializarElementos(); 280 | inicializarEventos(); 281 | consultarProductosServer(); 282 | //obtenerProductosStorage(); 283 | obtenerUsuarioStorage(); 284 | } 285 | 286 | main(); 287 | -------------------------------------------------------------------------------- /Clase 15 (AJAX y Fetch)/ejemplo_completo/productos.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "nombre": "Licensed Frozen Salad", 4 | "cantidad": 49, 5 | "precioVenta": "537.00", 6 | "precioCompra": "784.00", 7 | "fecha": "2022-04-04T06:08:01.498Z", 8 | "id": "7" 9 | }, 10 | { 11 | "nombre": "Licensed Fresh Bike", 12 | "cantidad": 91, 13 | "precioVenta": "989.00", 14 | "precioCompra": "816.00", 15 | "fecha": "2022-10-05T09:06:59.703Z", 16 | "id": "8" 17 | }, 18 | { 19 | "nombre": "Sleek Rubber Pants", 20 | "cantidad": 19, 21 | "precioVenta": "384.00", 22 | "precioCompra": "929.00", 23 | "fecha": "2022-10-05T16:43:45.364Z", 24 | "id": "9" 25 | }, 26 | { 27 | "nombre": "Recycled Fresh Shoes", 28 | "cantidad": 95, 29 | "precioVenta": "417.00", 30 | "precioCompra": "450.00", 31 | "fecha": "2022-10-05T11:01:19.684Z", 32 | "id": "10" 33 | }, 34 | { 35 | "nombre": "Fantastic Frozen Cheese", 36 | "cantidad": 12, 37 | "precioVenta": "41.00", 38 | "precioCompra": "692.00", 39 | "fecha": "2022-10-05T05:41:58.508Z", 40 | "id": "11" 41 | }, 42 | { 43 | "nombre": "Handmade Granite Ball", 44 | "cantidad": 73, 45 | "precioVenta": "511.00", 46 | "precioCompra": "626.00", 47 | "fecha": "2022-10-05T10:52:52.282Z", 48 | "id": "12" 49 | }, 50 | { 51 | "nombre": "Gorgeous Fresh Shoes", 52 | "cantidad": 13, 53 | "precioVenta": "723.00", 54 | "precioCompra": "756.00", 55 | "fecha": "2022-10-05T15:11:39.565Z", 56 | "id": "13" 57 | }, 58 | { 59 | "nombre": "Bespoke Soft Cheese", 60 | "cantidad": 59, 61 | "precioVenta": "662.00", 62 | "precioCompra": "378.00", 63 | "fecha": "2022-10-05T22:19:36.777Z", 64 | "id": "14" 65 | }, 66 | { 67 | "nombre": "Tasty Frozen Ball", 68 | "cantidad": 88, 69 | "precioVenta": "261.00", 70 | "precioCompra": "31.00", 71 | "fecha": "2022-10-05T23:20:32.106Z", 72 | "id": "15" 73 | }, 74 | { 75 | "nombre": "Electronic Concrete Computer", 76 | "cantidad": 96, 77 | "precioVenta": "562.00", 78 | "precioCompra": "557.00", 79 | "fecha": "2022-10-05T23:40:25.696Z", 80 | "id": "16" 81 | }, 82 | { 83 | "nombre": "Handcrafted Rubber Fish", 84 | "cantidad": 19, 85 | "precioVenta": "684.00", 86 | "precioCompra": "34.00", 87 | "fecha": "2022-10-05T06:59:45.213Z", 88 | "id": "17" 89 | }, 90 | { 91 | "nombre": "Recycled Frozen Hat", 92 | "cantidad": 55, 93 | "precioVenta": "3.00", 94 | "precioCompra": "349.00", 95 | "fecha": "2022-10-05T15:22:08.468Z", 96 | "id": "18" 97 | }, 98 | { 99 | "nombre": "Fantastic Fresh Sausages", 100 | "cantidad": 18, 101 | "precioVenta": "336.00", 102 | "precioCompra": "637.00", 103 | "fecha": "2022-10-05T11:52:15.595Z", 104 | "id": "19" 105 | }, 106 | { 107 | "nombre": "Refined Wooden Bike", 108 | "cantidad": 16, 109 | "precioVenta": "32.00", 110 | "precioCompra": "439.00", 111 | "fecha": "2022-10-05T06:00:37.481Z", 112 | "id": "20" 113 | }, 114 | { 115 | "nombre": "Electronic Bronze Fish", 116 | "cantidad": 57, 117 | "precioVenta": "556.00", 118 | "precioCompra": "883.00", 119 | "fecha": "2022-10-05T18:15:54.069Z", 120 | "id": "21" 121 | }, 122 | { 123 | "nombre": "Handcrafted Concrete Fish", 124 | "cantidad": 74, 125 | "precioVenta": "571.00", 126 | "precioCompra": "530.00", 127 | "fecha": "2022-10-05T20:29:51.583Z", 128 | "id": "22" 129 | }, 130 | { 131 | "nombre": "Ergonomic Metal Salad", 132 | "cantidad": 73, 133 | "precioVenta": "590.00", 134 | "precioCompra": "707.00", 135 | "fecha": "2022-10-05T08:38:09.457Z", 136 | "id": "23" 137 | }, 138 | { 139 | "nombre": "Fantastic Frozen Chicken", 140 | "cantidad": 77, 141 | "precioVenta": "668.00", 142 | "precioCompra": "205.00", 143 | "fecha": "2022-10-05T14:20:06.698Z", 144 | "id": "24" 145 | }, 146 | { 147 | "nombre": "Luxurious Soft Pizza", 148 | "cantidad": 27, 149 | "precioVenta": "919.00", 150 | "precioCompra": "356.00", 151 | "fecha": "2022-10-05T04:34:09.423Z", 152 | "id": "25" 153 | }, 154 | { 155 | "nombre": "Ergonomic Granite Bacon", 156 | "cantidad": 24, 157 | "precioVenta": "947.00", 158 | "precioCompra": "530.00", 159 | "fecha": "2022-10-05T22:23:51.762Z", 160 | "id": "26" 161 | }, 162 | { 163 | "nombre": "Luxurious Concrete Tuna", 164 | "cantidad": 81, 165 | "precioVenta": "888.00", 166 | "precioCompra": "249.00", 167 | "fecha": "2022-10-05T06:24:17.250Z", 168 | "id": "27" 169 | } 170 | ] 171 | -------------------------------------------------------------------------------- /Clase 15 (AJAX y Fetch)/ejemplo_completo/style.css: -------------------------------------------------------------------------------- 1 | .info{ 2 | background: blueviolet; 3 | } -------------------------------------------------------------------------------- /Clase 16 (Frameworks y nodejs) /ejemplo_node/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules -------------------------------------------------------------------------------- /Clase 16 (Frameworks y nodejs) /ejemplo_node/app.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | import bodyParser from "body-parser"; 4 | import express from "express"; 5 | 6 | //RUTAS 7 | import productRoutes from "./routes/products.js" 8 | 9 | const app = express(); 10 | app.use(bodyParser.urlencoded({extended:true})); 11 | app.use(bodyParser.json()); 12 | app.use(express.urlencoded({extended: false})); 13 | 14 | 15 | // configuración de cabeceras 16 | app.use((req,res,next)=>{ 17 | res.header('Access-Control-Allow-Origin','*'); 18 | res.header('Access-Control-Allow-Headers','Authorization, X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Controll-Allow-Request-Method'); 19 | res.header('Access-Control-Allow-Methods','GET, POST, OPTIONS, PUT, DELETE'); 20 | res.header('Allow','GET, POST, OPTIONS, PUT, DELETE'); 21 | next(); 22 | }); 23 | app.disable('etag'); 24 | 25 | //rutas base 26 | app.use('/api', productRoutes); 27 | 28 | export default app; -------------------------------------------------------------------------------- /Clase 16 (Frameworks y nodejs) /ejemplo_node/controllers/products.js: -------------------------------------------------------------------------------- 1 | import ProductModel from "../models/Product.js"; 2 | 3 | export async function getProducts(req, res) { 4 | try { 5 | let products = await ProductModel.find(); 6 | res.status(200).send({ products: products }); 7 | } catch (error) { 8 | return res.status(500).send({ message: error }); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Clase 16 (Frameworks y nodejs) /ejemplo_node/index.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | import mongoose from "mongoose"; 4 | import app from "./app.js"; 5 | const port = 3001; 6 | mongoose 7 | .connect(`mongodb://localhost:27017/bdUsers`, { 8 | useNewUrlParser: true, 9 | useUnifiedTopology: true, 10 | }) 11 | .then(() => { 12 | // start the Express server 13 | app.listen(port, async () => { 14 | console.log(`App is running at http://localhost:${port}`); 15 | }); 16 | }) 17 | .catch((error) => { 18 | console.log("🚀 ~ file: index.ts ~ line 16 ~ error", error); 19 | }); -------------------------------------------------------------------------------- /Clase 16 (Frameworks y nodejs) /ejemplo_node/models/Product.js: -------------------------------------------------------------------------------- 1 | import mongoose from "mongoose"; 2 | const Schema = mongoose.Schema; 3 | 4 | let ProductSchema = new Schema({ 5 | name: { type: String, required: true }, 6 | quantity: { type: Number, required: true }, 7 | purchasePrice: { type: Number, required: true }, 8 | salePrice: { type: Number, required: true }, 9 | date: { type: Date, required: false }, 10 | }); 11 | 12 | 13 | const ProductModel = mongoose.model('Product', ProductSchema); 14 | export default ProductModel; -------------------------------------------------------------------------------- /Clase 16 (Frameworks y nodejs) /ejemplo_node/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ejemplo_node", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "type": "module", 7 | "scripts": { 8 | "start": "nodemon index.js", 9 | "test": "echo \"Error: no test specified\" && exit 1" 10 | }, 11 | "author": "", 12 | "license": "ISC", 13 | "dependencies": { 14 | "body-parser": "^1.20.1", 15 | "express": "^4.18.2", 16 | "mongoose": "^6.6.5" 17 | }, 18 | "devDependencies": { 19 | "nodemon": "^2.0.20" 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Clase 16 (Frameworks y nodejs) /ejemplo_node/routes/products.js: -------------------------------------------------------------------------------- 1 | import express from "express"; 2 | import { getProducts } from "../controllers/products.js"; 3 | 4 | const api = express.Router(); 5 | 6 | api.get("/products", getProducts); 7 | 8 | export default api; 9 | -------------------------------------------------------------------------------- /Clase 16 (Frameworks y nodejs) /ejemplo_react/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /Clase 16 (Frameworks y nodejs) /ejemplo_react/README.md: -------------------------------------------------------------------------------- 1 | # Getting Started with Create React App 2 | 3 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 4 | 5 | ## Available Scripts 6 | 7 | In the project directory, you can run: 8 | 9 | ### `npm start` 10 | 11 | Runs the app in the development mode.\ 12 | Open [http://localhost:3000](http://localhost:3000) to view it in your browser. 13 | 14 | The page will reload when you make changes.\ 15 | You may also see any lint errors in the console. 16 | 17 | ### `npm test` 18 | 19 | Launches the test runner in the interactive watch mode.\ 20 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 21 | 22 | ### `npm run build` 23 | 24 | Builds the app for production to the `build` folder.\ 25 | It correctly bundles React in production mode and optimizes the build for the best performance. 26 | 27 | The build is minified and the filenames include the hashes.\ 28 | Your app is ready to be deployed! 29 | 30 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 31 | 32 | ### `npm run eject` 33 | 34 | **Note: this is a one-way operation. Once you `eject`, you can't go back!** 35 | 36 | If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 37 | 38 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own. 39 | 40 | You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it. 41 | 42 | ## Learn More 43 | 44 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 45 | 46 | To learn React, check out the [React documentation](https://reactjs.org/). 47 | 48 | ### Code Splitting 49 | 50 | This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting) 51 | 52 | ### Analyzing the Bundle Size 53 | 54 | This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size) 55 | 56 | ### Making a Progressive Web App 57 | 58 | This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app) 59 | 60 | ### Advanced Configuration 61 | 62 | This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration) 63 | 64 | ### Deployment 65 | 66 | This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) 67 | 68 | ### `npm run build` fails to minify 69 | 70 | This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify) 71 | -------------------------------------------------------------------------------- /Clase 16 (Frameworks y nodejs) /ejemplo_react/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ejemplo_peticion", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@testing-library/jest-dom": "^5.16.5", 7 | "@testing-library/react": "^13.4.0", 8 | "@testing-library/user-event": "^13.5.0", 9 | "react": "^18.2.0", 10 | "react-dom": "^18.2.0", 11 | "react-scripts": "5.0.1", 12 | "web-vitals": "^2.1.4" 13 | }, 14 | "scripts": { 15 | "start": "react-scripts start", 16 | "build": "react-scripts build", 17 | "test": "react-scripts test", 18 | "eject": "react-scripts eject" 19 | }, 20 | "eslintConfig": { 21 | "extends": [ 22 | "react-app", 23 | "react-app/jest" 24 | ] 25 | }, 26 | "browserslist": { 27 | "production": [ 28 | ">0.2%", 29 | "not dead", 30 | "not op_mini all" 31 | ], 32 | "development": [ 33 | "last 1 chrome version", 34 | "last 1 firefox version", 35 | "last 1 safari version" 36 | ] 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Clase 16 (Frameworks y nodejs) /ejemplo_react/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JesusBrito/comision-34015-javascript/63d372d3a93333c1e79978d73ba60ca7f9399bb9/Clase 16 (Frameworks y nodejs) /ejemplo_react/public/favicon.ico -------------------------------------------------------------------------------- /Clase 16 (Frameworks y nodejs) /ejemplo_react/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /Clase 16 (Frameworks y nodejs) /ejemplo_react/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JesusBrito/comision-34015-javascript/63d372d3a93333c1e79978d73ba60ca7f9399bb9/Clase 16 (Frameworks y nodejs) /ejemplo_react/public/logo192.png -------------------------------------------------------------------------------- /Clase 16 (Frameworks y nodejs) /ejemplo_react/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JesusBrito/comision-34015-javascript/63d372d3a93333c1e79978d73ba60ca7f9399bb9/Clase 16 (Frameworks y nodejs) /ejemplo_react/public/logo512.png -------------------------------------------------------------------------------- /Clase 16 (Frameworks y nodejs) /ejemplo_react/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /Clase 16 (Frameworks y nodejs) /ejemplo_react/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /Clase 16 (Frameworks y nodejs) /ejemplo_react/src/App.js: -------------------------------------------------------------------------------- 1 | import { useEffect, useState } from "react"; 2 | 3 | function App() { 4 | const [products, setProducts] = useState([]); 5 | useEffect(() => { 6 | getDataFromApi(); 7 | }, []); 8 | 9 | async function getDataFromApi() { 10 | try { 11 | const response = await fetch("http://localhost:3001/api/products"); 12 | const dataResponse = await response.json(); 13 | setProducts(dataResponse.products); 14 | } catch (error) { 15 | console.log(error); 16 | } 17 | } 18 | return ( 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | {products.map((product) => ( 30 | 31 | 32 | 33 | 34 | 35 | 36 | ))} 37 | 38 |
NombrePrecio compraPrecio ventaCantidad
{product.name}{product.purchasePrice}{product.salePrice}{product.quantity}
39 | ); 40 | } 41 | 42 | export default App; 43 | -------------------------------------------------------------------------------- /Clase 16 (Frameworks y nodejs) /ejemplo_react/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom/client'; 3 | import App from './App'; 4 | 5 | const root = ReactDOM.createRoot(document.getElementById('root')); 6 | root.render( 7 | 8 | 9 | 10 | ); 11 | -------------------------------------------------------------------------------- /Clase 2 (Control de flujos)/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JesusBrito/comision-34015-javascript/63d372d3a93333c1e79978d73ba60ca7f9399bb9/Clase 2 (Control de flujos)/.DS_Store -------------------------------------------------------------------------------- /Clase 2 (Control de flujos)/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /Clase 2 (Control de flujos)/index.js: -------------------------------------------------------------------------------- 1 | //================ESTRUCTURA IF================ 2 | // const EDAD = prompt("Ingresa tu edad") 3 | 4 | // if(EDAD == 18){ 5 | // alert("Puedes consumir alcohol") 6 | // } 7 | 8 | // if(EDAD == 18) { 9 | // alert("Puedes consumir alcohol") 10 | // }else{ 11 | // alert("No puedes consumir alcohol") 12 | // } 13 | 14 | //================CONDICIONALES ANIDADOS================ 15 | // let vidaPersonaje = 30; 16 | 17 | // if (vidaPersonaje == 100) { 18 | // alert("La vida está completa") 19 | // } else if (vidaPersonaje == 50) { 20 | // alert("La vida está a la mitad") 21 | // } else if (vidaPersonaje == 0) { 22 | // alert("Muerto"); 23 | // } else if (vidaPersonaje < 20) { 24 | // alert("La vida esta peligrosamente baja") 25 | // }else { 26 | // alert("La vida del personaje es: " + vidaPersonaje) 27 | // } 28 | 29 | //================OPERADORES DE COMPARACIÓN================ 30 | 31 | //================MAYOR O IGUAL================ 32 | // const EDAD = prompt("Ingresa tu edad") 33 | // if(EDAD >= 18) { 34 | // alert("Puedes consumir alcohol") 35 | // }else{ 36 | // alert("No puedes consumir alcohol") 37 | // } 38 | 39 | //================DIFERENTE================ 40 | // const NUMERO_UNO = prompt("Ingrese el primer número") 41 | // const NUMERO_DOS = prompt("Ingrese el segundo número") 42 | // if(NUMERO_UNO != NUMERO_DOS){ 43 | // alert("Los números no son iguales") 44 | // }else { 45 | // alert("Los números son iguales") 46 | // } 47 | 48 | //================ESTRICTAMENTE IGUAL================ 49 | // let NUMERO_UNO = 1 50 | // let NUMERO_DOS = "1" 51 | 52 | // if (NUMERO_UNO == NUMERO_DOS) { 53 | // alert("Los números son iguales") 54 | // } else { 55 | // alert("Los números no son iguales") 56 | // } 57 | 58 | // if (NUMERO_UNO === NUMERO_DOS) { 59 | // alert("Los números son iguales") 60 | // } else { 61 | // alert("Los números no son iguales") 62 | // } 63 | 64 | //================OPERADORES LÓGICOS================ 65 | 66 | //================AND================ 67 | // const USUARIO = prompt("Ingresa tu usuario") 68 | // const PASSWORD = prompt("Ingresa tu contraseña") 69 | 70 | // if(USUARIO == "admin" && PASSWORD == "123456"){ 71 | // alert("Bienvenido" + USUARIO) 72 | // }else{ 73 | // alert("Usuario o contraseña incorrectos") 74 | // } 75 | 76 | //================OR================ 77 | // const NOMBRE = prompt("Ingresa tu nombre") 78 | // const ANIO = prompt("Ingresa tu año de nacimiento") 79 | // const ANIO_ACTUAL = 2022 80 | 81 | // if(NOMBRE == "" || ANIO == ""){ 82 | // alert("Ingrese toda la información") 83 | // }else{ 84 | // const EDAD = ANIO_ACTUAL - ANIO 85 | // alert("Hola " + NOMBRE + " tu edad es: "+ EDAD) 86 | // } 87 | 88 | //================NOT================ 89 | // const EDAD = prompt("Ingresa tu edad") 90 | 91 | // let esMayor = EDAD >= 18 92 | 93 | // console.log("Variable original: "+ esMayor) 94 | // console.log("Variable aplicando operador not: "+ !esMayor) 95 | 96 | 97 | //================CONDICIONALES COMPUESTAS AND OR================ 98 | let valorUno = true 99 | let valorDos = true 100 | let valorTres = true 101 | 102 | if(valorUno == true && (valorDos == false || valorTres == false)){ 103 | alert("verdadero") 104 | }else{ 105 | alert("falso") 106 | } -------------------------------------------------------------------------------- /Clase 3 (Cilclos e iteraciones)/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /Clase 3 (Cilclos e iteraciones)/index.js: -------------------------------------------------------------------------------- 1 | //================COMPARACIÓN PROCESO REPETITIVO================ 2 | 3 | // console.log(1) 4 | // console.log(2) 5 | // console.log(3) 6 | // console.log(4) 7 | // console.log(5) 8 | 9 | // for (let index = 1; index <= 5; index++) { 10 | // console.log(index) 11 | // } 12 | 13 | //================CALCULAR PROMEDIO DADO UN NUMERO DE CALIFICACIONES================ 14 | // let numeroCalificaciones = prompt("¿Cuantas calificaciones son?"); 15 | // let sumatoria = 0; 16 | // let promedio = 0; 17 | 18 | // for (let index = 1; index < numeroCalificaciones; index++) { 19 | // let calificacion = prompt("Ingrese la calificación " + index); 20 | // sumatoria = sumatoria + parseFloat(calificacion); 21 | // } 22 | // promedio = sumatoria / numeroCalificaciones; 23 | 24 | // alert("El promedio es: "+ promedio); 25 | 26 | //================BREAK================ 27 | /* 28 | Escribir un programa que imprima todos 29 | los números hasta encontrar el primer divisor 30 | entre 10 31 | */ 32 | 33 | // for (let index = 1; index <= 30; index++) { 34 | // if (index % 10 == 0) { 35 | // break; 36 | // } 37 | // console.log(index); 38 | // } 39 | 40 | //================CONTINUE================ 41 | /* 42 | Escribir un programa que imprima todos 43 | los números pares del 1 al 100 44 | */ 45 | 46 | // for (let index = 1; index <= 10; index++) { 47 | // if (index % 2 != 0) { 48 | // continue; 49 | // } 50 | // console.log(index); 51 | // } 52 | 53 | //================EJERCICIO PRÁCTICO FOR================ 54 | /* 55 | Escribir un programa que muestre en pantalla 56 | los números del 1 al 100, sustituyendo los 57 | múltiplos de 3 por la palabra “fizz”, 58 | los múltiplos de 5 por “buzz” y 59 | los múltiplos de ambos, es decir, 60 | los múltiplos de 3 y 5 (o de 15), 61 | por la palabra “fizzbuzz”. 62 | */ 63 | 64 | // for (let index = 1; index <= 100; index++) { 65 | // if (index % 3 == 0 && index % 5 == 0) { 66 | // console.log("fizzbuzz"); 67 | // } else if (index % 3 == 0) { 68 | // console.log("fizz"); 69 | // } else if (index % 5 == 0) { 70 | // console.log("buzz"); 71 | // } else { 72 | // console.log(index); 73 | // } 74 | // } 75 | 76 | //================WHILE================ 77 | 78 | // let entrada = prompt("Ingresar un dato (ESC para salir)"); 79 | // while (entrada != "ESC") { 80 | // alert("El usuario ingresó " + entrada); 81 | // entrada = prompt("Ingresar otro dato"); 82 | // } 83 | 84 | //================ALERTA================ 85 | /* 86 | NO DES COMENTAR, PUEDE CAUSAR BLOQUEOS 87 | EN TU NAVEGADOR LOS BUCLES INFINITOS MUY RARA VEZ 88 | SON ÚTILES Y DEBEN EVITARSE 89 | */ 90 | 91 | /* 92 | while(true){ 93 | alert("Este es un mensaje infinito") 94 | } 95 | */ 96 | 97 | //================DO WHILE================ 98 | 99 | // let nombre = ""; 100 | 101 | // do { 102 | // nombre = prompt("Ingresar un dato nombre"); 103 | // if (nombre !== "") { 104 | // alert("El nombre ingresado es: " + nombre); 105 | // } 106 | // } while (nombre != ""); 107 | 108 | //================ SWITCH ================ 109 | 110 | // let valor = 1; 111 | // switch (valor) { 112 | // case 1: 113 | // console.log("Valor 1"); 114 | // break; 115 | // case 2: 116 | // console.log("Valor 2"); 117 | // break; 118 | // case 3: 119 | // console.log("Valor 3"); 120 | // break; 121 | // default: 122 | // console.log("Valor Default") 123 | // break; 124 | // } 125 | 126 | // let seleccionUsuario = parseInt( 127 | // prompt( 128 | // "Que desea comer: \n 1.Una Hamburguesa \n 2.Un Taco \n 3.Un Hot dog \n 4.Unos Nachos" 129 | // ) 130 | // ); 131 | // if (seleccionUsuario === 1) { 132 | // alert("Usted selecciono una Hamburguesa"); 133 | // } else if (seleccionUsuario === 2) { 134 | // alert("Usted selecciono un Taco"); 135 | // } else if (seleccionUsuario === 3) { 136 | // alert("Usted selecciono un Hot dog"); 137 | // } else if (seleccionUsuario === 4) { 138 | // alert("Usted selecciono un Hot dog"); 139 | // } 140 | 141 | // let seleccionUsuario = parseInt( 142 | // prompt( 143 | // "Que desea comer: \n 1.Una Hamburguesa \n 2.Un Taco \n 3.Un Hot dog \n 4.Unos Nachos" 144 | // ) 145 | // ); 146 | 147 | // switch (seleccionUsuario) { 148 | // case 1: 149 | // alert("Usted selecciono una Hamburguesa"); 150 | // break; 151 | // case 2: 152 | // alert("Usted selecciono un Taco"); 153 | // break; 154 | // case 3: 155 | // alert("Usted selecciono un Hot dog"); 156 | // break; 157 | // case 4: 158 | // alert("Usted selecciono un Hot dog"); 159 | // break; 160 | // default: 161 | // alert("Opción inválida"); 162 | // break; 163 | // } 164 | -------------------------------------------------------------------------------- /Clase 4 (Funciones)/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /Clase 4 (Funciones)/index.js: -------------------------------------------------------------------------------- 1 | //================FUNCIÓN SENCILLA================ 2 | 3 | // function iniciarSesion() { 4 | // const USUARIO = prompt("Ingresa tu usuario"); 5 | // const PASSWORD = prompt("Ingresa tu contraseña"); 6 | 7 | // if (USUARIO == "admin" && PASSWORD == "123456") { 8 | // alert("Bienvenido " + USUARIO); 9 | // } else { 10 | // alert("Usuario o contraseña incorrectos"); 11 | // } 12 | // } 13 | 14 | // iniciarSesion(); 15 | 16 | //================FUNCIÓN CON PARÁMETROS================ 17 | 18 | // function sumarDosNumeros(numeroUno, numeroDos) { 19 | // let suma = numeroUno + numeroDos; 20 | // alert("La suma es: " + suma); 21 | // } 22 | 23 | // const NUMERO_UNO = parseFloat(prompt("Ingresar el primer número")); 24 | // const NUMERO_DOS = parseFloat(prompt("Ingresar el segundo número")); 25 | 26 | // sumarDosNumeros(NUMERO_UNO, NUMERO_DOS); 27 | 28 | //================FUNCIÓN CON RETURN================ 29 | 30 | // function sumarCalificaciones( 31 | // calificacionUno, 32 | // calificacionDos, 33 | // calificacionTres 34 | // ) { 35 | // let sumatoria = calificacionUno + calificacionDos + calificacionTres; 36 | // return sumatoria; 37 | // } 38 | // function mostrarPromedio() { 39 | // let resultadoSumatoria = sumarCalificaciones(10, 8, 9); 40 | // let promedio = resultadoSumatoria / 3; 41 | // alert("El promedio es: " + promedio); 42 | // } 43 | // mostrarPromedio(); 44 | 45 | //================CALCULADORA================ 46 | 47 | // function suma(numeroUno, numeroDos) { 48 | // let resultado = numeroUno + numeroDos; 49 | // return resultado; 50 | // } 51 | // function resta(numeroUno, numeroDos) { 52 | // let resultado = numeroUno - numeroDos; 53 | // return resultado; 54 | // } 55 | // function multiplicacion(numeroUno, numeroDos) { 56 | // let resultado = numeroUno * numeroDos; 57 | // return resultado; 58 | // } 59 | // function division(numeroUno, numeroDos) { 60 | // let resultado = numeroUno / numeroDos; 61 | // return resultado; 62 | // } 63 | // function mostrarResultado(resultado) { 64 | // alert("El resultado es: " + resultado); 65 | // } 66 | 67 | // function calculadora() { 68 | // let opcion = parseInt( 69 | // prompt( 70 | // "Bienvenido, seleccione la opción \n 1.-Suma\n 2.- Resta\n 3.-Multiplicación\n 4.- División " 71 | // ) 72 | // ); 73 | // const NUMERO_UNO = parseFloat(prompt("Ingresar el primer número")); 74 | // const NUMERO_DOS = parseFloat(prompt("Ingresar el segundo número")); 75 | 76 | // switch (opcion) { 77 | // case 1: 78 | // let resultadoSuma = suma(NUMERO_UNO, NUMERO_DOS); 79 | // mostrarResultado(resultadoSuma); 80 | // break; 81 | // case 2: 82 | // let resultadoResta = resta(NUMERO_UNO, NUMERO_DOS); 83 | // mostrarResultado(resultadoResta); 84 | // break; 85 | // case 3: 86 | // let resultadoMultiplicacion = multiplicacion(NUMERO_UNO, NUMERO_DOS); 87 | // mostrarResultado(resultadoMultiplicacion); 88 | // break; 89 | // case 4: 90 | // let resultadoDivision = division(NUMERO_UNO, NUMERO_DOS); 91 | // mostrarResultado(resultadoDivision); 92 | // break; 93 | // default: 94 | // alert("Opción incorrecta"); 95 | // break; 96 | // } 97 | // } 98 | 99 | // calculadora(); 100 | 101 | //================SCOPE================ 102 | 103 | let resultado = 0; 104 | 105 | function sumar(primerNumero, segundoNumero) { 106 | resultado = primerNumero + segundoNumero; 107 | } 108 | 109 | sumar(5, 6); 110 | 111 | //Se puede acceder a la variable resultado porque es global 112 | alert(resultado); 113 | 114 | function sumar(primerNumero, segundoNumero) { 115 | let resultado = primerNumero + segundoNumero; 116 | } 117 | 118 | alert(resultado); 119 | 120 | let nombre = "John Doe"; // variable global 121 | 122 | function saludar() { 123 | let nombre = "Juan"; // variable local 124 | alert(nombre); 125 | } 126 | 127 | //Accede a nombre global 128 | alert(nombre); // → “John Doe” 129 | 130 | //Accede a nombre local 131 | saludar(); // → “Juan” 132 | 133 | //================FUNCIONES ANÓNIMAS================ 134 | 135 | // const suma = function (valorUno, valorDos) { 136 | // let resultado = valorUno + valorDos; 137 | // return resultado; 138 | // }; 139 | 140 | // alert("El resultado es: " + suma(15, 20)); 141 | 142 | //================ARROW FUNCTIONS================ 143 | 144 | // const suma = (valorUno, valorDos) => { 145 | // let resultado = valorUno + valorDos; 146 | // return resultado; 147 | // }; 148 | 149 | // alert("El resultado es: " + suma(15, 20)); 150 | 151 | // const suma = (valorUno, valorDos) => valorUno + valorDos; 152 | 153 | // alert("El resultado es: " + suma(15, 20)); 154 | 155 | //================EJEMPLO COMPLETO CON ARROW FUNCTIONS================ 156 | 157 | let precioProducto = 0; 158 | let descuento = 0; 159 | 160 | const IVA = 0.16; 161 | const suma = (valorUno, valorDos) => valorUno + valorDos; 162 | const resta = (valorUno, valorDos) => valorUno - valorDos; 163 | const calcularIva = (subtotal) => subtotal * IVA; 164 | const mostrarPrecioFinal = (precio) => alert(precio); 165 | 166 | const solicitarValores = () => { 167 | precioProducto = parseFloat(prompt("Ingrese el precio del producto")); 168 | descuento = parseFloat(prompt("Ingrese el descuento en pesos")); 169 | }; 170 | 171 | solicitarValores(); 172 | 173 | let subtotal = resta(precioProducto, descuento); 174 | const VALOR_IVA = calcularIva(subtotal); 175 | const PRECIO_FINAL = suma(subtotal, VALOR_IVA); 176 | 177 | mostrarPrecioFinal(PRECIO_FINAL); 178 | -------------------------------------------------------------------------------- /Clase 5 (Objetos)/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /Clase 5 (Objetos)/index.js: -------------------------------------------------------------------------------- 1 | //================ OBJETOS ================ 2 | 3 | // const persona = { 4 | // nombre: "Jesus", 5 | // apellido: "Brito", 6 | // edad: 25, 7 | // pais: "México", 8 | // ciudad: "CDMX", 9 | // esDesarrollador: true, 10 | // }; 11 | 12 | // console.log(persona); 13 | 14 | // console.log("Nombre persona " + persona.nombre); 15 | // console.log("Edad persona " + persona["edad"]); 16 | 17 | // persona.edad = 80; 18 | // console.log("Nueva edad persona " + persona.edad); 19 | 20 | // persona["vida"] = 120; 21 | // console.log("Nueva edad persona " + persona.edad); 22 | 23 | //================ FUNCIÓN CONSTRUCTORA ================ 24 | 25 | // function Persona(nombre, apellido, edad, pais, ciudad, esDesarrollador) { 26 | // this.nombre = nombre; 27 | // this.apellido = apellido; 28 | // this.edad = edad; 29 | // this.pais = pais; 30 | // this.ciudad = ciudad; 31 | // this.esDesarrollador = esDesarrollador; 32 | // this.aumentarEdad = (anios) => this.edad + anios; 33 | // this.disminuirEdad = (anios) => this.edad - anios; 34 | // this.saludar = () => 35 | // `Hola mi nombre es ${this.nombre} ${this.apellido}, mi edad es: ${this.edad}`; 36 | // } 37 | 38 | // function crearPersona() { 39 | // let nombre = prompt("Ingresa tu nombre"); 40 | // let apellido = prompt("Ingresa tu apellido"); 41 | // let edad = prompt("Ingresa tu edad"); 42 | // let pais = prompt("Ingresa tu pais"); 43 | // let ciudad = prompt("Ingresa tu ciudad"); 44 | // let esDesarrollador = prompt("¿Eres desarrollador? (Si/No)"); 45 | 46 | // if (esDesarrollador.toLowerCase() == "Si") { 47 | // esDesarrollador = true; 48 | // } else { 49 | // esDesarrollador = false; 50 | // } 51 | 52 | // const objetoPersona = new Persona( 53 | // nombre, 54 | // apellido, 55 | // edad, 56 | // pais, 57 | // ciudad, 58 | // esDesarrollador 59 | // ); 60 | // return objetoPersona; 61 | // } 62 | 63 | // const personaUno = crearPersona(); 64 | // console.info(personaUno); 65 | 66 | //================ OPERADOR IN ================ 67 | 68 | // const isNombreEnObjeto = "nombre" in personaUno; 69 | // console.log("La propiedad nombre existe en el objeto?: " + isNombreEnObjeto); 70 | 71 | // const isOrigenEnObjeto = "origen" in personaUno; 72 | // console.log("La propiedad origen existe en el objeto?: " + isOrigenEnObjeto); 73 | 74 | //================ OPERADOR FOR IN ================ 75 | 76 | // for (const propiedad in personaUno) { 77 | // console.log(`${propiedad}: ${personaUno[propiedad]}`); 78 | // } 79 | 80 | //================ CLASES ================ 81 | 82 | class Producto { 83 | constructor(nombre, precio, cantidad) { 84 | this.nombre = nombre; 85 | this.precio = precio; 86 | this.cantidad = cantidad; 87 | this.vendido = false; 88 | } 89 | aumentarPrecio(precioAumentar) { 90 | this.precio += precioAumentar; 91 | } 92 | vender() { 93 | this.vendido = true; 94 | } 95 | disminuirPrecio = (precioDiminuir) => (this.precio -= precioDiminuir); 96 | aplicarPromo = (promoCode) => { 97 | if (promoCode === "DESCUENTO100") { 98 | this.precio -= this.precio * 0.05; 99 | } 100 | }; 101 | reducirStock = (cantidad) => (this.cantidad -= cantidad); 102 | aumentarStock = (cantidad) => (this.cantidad += cantidad); 103 | } 104 | 105 | let nombreProducto = "Laptop HP"; 106 | let precioCompra = 800; 107 | let precioVenta = 10; 108 | 109 | const LAPTOP = new Producto(nombreProducto, precioCompra, precioVenta); 110 | 111 | LAPTOP.aumentarPrecio(100); 112 | console.log("Precio laptop: " + LAPTOP.precio); 113 | 114 | LAPTOP.vender(); 115 | 116 | console.log("Estatus vendido laptop: " + LAPTOP.vendido); 117 | 118 | LAPTOP.aplicarPromo("DESCUENTO100"); 119 | console.log("Precio laptop: " + LAPTOP.precio); 120 | -------------------------------------------------------------------------------- /Clase 6 (Arrays)/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /Clase 6 (Arrays)/index.js: -------------------------------------------------------------------------------- 1 | //================ DECLARAR UN ARRAY ================ 2 | 3 | // let arrayCiudades = []; 4 | 5 | // let arrayPalabras = ["Hola", "Mundo", "desde", "Javascript"]; 6 | 7 | // let arrayNumeros = [1, 2, 3, 4]; 8 | 9 | // let arrayBooleanos = [true, false, false]; 10 | 11 | // let arrayMixto = ["Hola", false, 4]; 12 | 13 | //================ ACCEDER A LOS ELEMENTOS DE UN ARRAY ================ 14 | 15 | //-> indice, es la poción del array en donde se encuentra un elemento 16 | //-> los indices o posiciones inician en 0 17 | 18 | // let arrayPaises = ["Argentina", "Venezuela", "Colombia", "México"]; 19 | 20 | // console.log(arrayPaises[0]) 21 | 22 | // console.log(arrayPaises[0] + arrayPaises[1]) 23 | 24 | //================ IMPRIMIR TODOS LOS ELEMENTOS DE UN ARRAY ================ 25 | //->length, propiedad para obtener el tamaño de un array 26 | 27 | // console.log(arrayPaises.length) 28 | 29 | // for (let index = 0; index < arrayPaises.length; index++) { 30 | // console.log("indice: "+ index + " : "+ arrayPaises[index]) 31 | // } 32 | 33 | //================ AGREGAR ELEMENTO A UN ARRAY ================ 34 | 35 | //push->Agrega elemento al final del array 36 | // let arrayNombres = ["Pedro", "Juan", "David"]; 37 | 38 | // console.log(arrayNombres); 39 | // arrayNombres.push("Alan"); 40 | // console.log(arrayNombres); 41 | 42 | //unshift->Agrega elemento al inicio del array 43 | // arrayNombres.push("Luis"); 44 | // console.log(arrayNombres); 45 | 46 | //================ ELIMINAR ELEMENTO DE UN ARRAY ================ 47 | 48 | //pop->Elimina elemento al final del array 49 | // arrayNombres.pop(); 50 | // console.log(arrayNombres); 51 | 52 | //shift->Elimina elemento al inicio del array 53 | // arrayNombres.shift(); 54 | // console.log(arrayNombres); 55 | 56 | //================ ELIMINAR ELEMENTOS DE UN ARRAY ================ 57 | // let arrayProductos = ["Laptop", "PC", "Celular"]; 58 | 59 | //Primer parámetro el indice a partir del cual se va a eliminar, 60 | //el segundo es cuantos elementos se van a eliminar 61 | 62 | // arrayProductos.splice(0, 2); 63 | // console.log("Nueva lista:"); 64 | // console.log(nuevaLista); 65 | 66 | //================ CONCATENAR TODOS LOS ELEMENTOS DE UN ARRAY ================ 67 | // let arrayProductos = ["Laptop", "PC", "Celular"]; 68 | 69 | // let arrayConcatenado = arrayProductos.join("-") 70 | // console.log(arrayConcatenado) 71 | 72 | //================ CONCATENAR DOS ARRAYS ================ 73 | // let arrayProductos = ["Laptop", "PC", "Celular"]; 74 | // let arrayProductosDos = ["iPhone", "iPad", "Samsung s22"]; 75 | 76 | // let arrayCombinado = arrayProductos.concat(arrayProductosDos); 77 | 78 | // console.log(arrayCombinado) 79 | 80 | //================ COPIAR UNA PARTE DEL ARRAY ================ 81 | //Primer parámetro el indice a partir del cual se va a comenzar, 82 | //a copiar, el segundo es en donde se va a finalizar pero el fin 83 | //no está incluido 84 | 85 | // let arrayProductos = ["Laptop", "PC", "Celular"]; 86 | // let porcionArray = arrayProductos.slice(1, 2) 87 | 88 | //================ CONOCER EL INDEX DE UN ELEMENTO EN EL ARRAY ================ 89 | 90 | // let arrayProductos = ["Laptop", "PC", "Celular"]; 91 | 92 | // console.log(arrayProductos.indexOf("Laptop")) 93 | // console.log(arrayProductos.indexOf("Samsung S22")) 94 | 95 | //================ CONOCER SI UN ELEMENTO EXISTE EN EL ARRAY ================ 96 | 97 | // let arrayProductos = ["Laptop", "PC", "Celular"]; 98 | 99 | // console.log(arrayProductos.includes("Laptop")) 100 | // console.log(arrayProductos.includes("Samsung S22")) 101 | 102 | //================ INVIERTE UN ARRAY ================ 103 | 104 | // let arrayProductos = ["Laptop", "PC", "Celular"]; 105 | 106 | // //Reverse es destructivo, modifica el array original 107 | // console.log(arrayProductos.reverse()) 108 | 109 | //================ FOR OF ================ 110 | // let arrayProductos = ["Laptop", "PC", "Celular"]; 111 | // for (const producto of arrayProductos) { 112 | // console.log(producto); 113 | // } 114 | 115 | //================ ELIMINAR UN ELEMENTO ESPECIFICO DE UN ARRAY ================ 116 | 117 | const nombres = ["Rita", "Pedro", "Miguel", "Ana", "Vanesa"]; 118 | 119 | function eliminarElemento(nombre) { 120 | let index = nombres.indexOf(nombre); 121 | if (index != -1) { 122 | nombres.splice(index, 1); 123 | } 124 | } 125 | 126 | let valorAEliminar = prompt("Ingrese un nombre"); 127 | eliminarElemento(valorAEliminar); 128 | console.log(nombres); 129 | 130 | //================ EJEMPLO COMPLETO ================ 131 | 132 | class Producto { 133 | constructor(nombre, precioCompra, precioVenta, cantidad) { 134 | this.nombre = nombre.toUpperCase(); 135 | this.precioCompra = precioCompra; 136 | this.precioVenta = precioVenta; 137 | this.cantidad = cantidad; 138 | } 139 | calcularCosto = () => this.cantidad * this.precioCompra; 140 | } 141 | 142 | function agregarProductos() { 143 | let numeroProductos = parseInt( 144 | prompt("Cuantos productos necesita registrar") 145 | ); 146 | let productos = []; 147 | for (let index = 0; index < numeroProductos; index++) { 148 | let nombre = prompt("Ingrese el nombre"); 149 | let precioCompra = prompt("Ingrese el precio de compra"); 150 | let precioVenta = prompt("Ingrese el precio de venta"); 151 | let cantidad = prompt("Ingrese la cantidad"); 152 | let productoARegistrar = new Producto( 153 | nombre, 154 | precioCompra, 155 | precioVenta, 156 | cantidad 157 | ); 158 | productos.push(productoARegistrar); 159 | } 160 | return productos; 161 | } 162 | 163 | function mostrarProductos(productos) { 164 | for (const producto of productos) { 165 | console.log(producto); 166 | console.log(producto.nombre); 167 | } 168 | } 169 | 170 | function calcularCosto(productos) { 171 | let sumatoriaCosto = 0; 172 | for (const producto of productos) { 173 | sumatoriaCosto += producto.calcularCosto(); 174 | } 175 | return sumatoriaCosto; 176 | } 177 | 178 | function main() { 179 | let productos = agregarProductos(); 180 | mostrarProductos(productos); 181 | let costoAlmacen = calcularCosto(productos); 182 | alert("El costo total del almacén es: " + costoAlmacen); 183 | } 184 | 185 | main(); 186 | -------------------------------------------------------------------------------- /Clase 7 (HOF)/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /Clase 8 (DOM)/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 15 | 16 | 17 |
18 |
19 |

Ejemplo uno

20 |
21 |
22 |
23 |

Ejemplo dos

24 |
25 |

Este es un parrafo

26 |
27 |
28 |
29 |
30 |

Ejemplo tres

31 |
32 |

Contenedor uno

33 |
34 |
35 |

Contenedor dos

36 |
37 |
38 |

Contenedor tres

39 |
40 |
41 |

Contenedor cuatro

42 |
43 |
44 |
45 |
46 |

Ejemplo cuatro

47 | 52 |
53 |
54 |

55 |
56 |

Este es un parrafo

57 |
58 |
59 |

Ejemplo cinco

60 |

Este es un parrafo

61 |
62 |
63 |
64 |

Ejemplo seis

65 |
66 |
67 |
68 |

Ejemplo siete

69 |
70 |
71 |
72 |

Ejemplo ocho

73 |
74 |
75 | 78 | 84 |
85 |
86 | 87 | 93 |
94 |
95 |
96 |
97 |
98 |

Ejemplo completo

99 | 100 |
101 |
102 |
103 | 108 | 109 | 110 | 111 | -------------------------------------------------------------------------------- /Clase 8 (DOM)/index.js: -------------------------------------------------------------------------------- 1 | //================ OBJETO GLOBAL document ================ 2 | console.log(document); 3 | 4 | //================ NODOS RAÍZ ================ 5 | console.log(document.head); 6 | console.log(document.body); 7 | 8 | //================ OBTENER ELEMENTO POR ID ================ 9 | 10 | let divUno = document.getElementById("contenedor-ejemplo-dos"); 11 | let parrafoUno = document.getElementById("parrafo1"); 12 | console.log(divUno.innerHTML); 13 | console.log(parrafoUno.innerHTML); 14 | 15 | //================ OBTENER ELEMENTOS POR CLASS NAME ================ 16 | 17 | let listaDivs = document.getElementsByClassName("contenedor-ejemplo-tres"); 18 | console.log(listaDivs); 19 | 20 | for (const div of listaDivs) { 21 | console.log(div.innerHTML); 22 | } 23 | 24 | //================ OBTENER ELEMENTO POR TAG NAME ================ 25 | 26 | let listaItems = document.getElementsByTagName("li"); 27 | console.log(listaItems); 28 | for (const item of listaItems) { 29 | console.log(item.innerText); 30 | } 31 | 32 | //================ OBTENER ELEMENTO USANDO QUERY SELECTOR ================ 33 | 34 | // let parrafo = document.querySelector("#contenedor p") 35 | 36 | // let contenedor = document.querySelector("#contenedor") 37 | 38 | // parrafo = document.querySelector(".texto") 39 | 40 | //================ AGREGAR TEXTO A UN PÁRRAFO MEDIANTE JAVASCRIPT ================ 41 | 42 | // let parrafo = document.getElementById("parrafo-cinco"); 43 | // console.log(parrafo.innerText); 44 | // parrafo.innerText = "Hola!!, Este es un parrafo modificado"; 45 | // console.log(parrafo.innerText); 46 | 47 | //================ MODIFICAR EL INNER HTML MEDIANTE JAVASCRIPT ================ 48 | 49 | // let contenedor = document.getElementById("contenedor-seis"); 50 | // contenedor.innerHTML = 51 | // "

Hola!

este es un texto agregado desde Javascript

"; 52 | 53 | //================ AGREGAR CLASES CSS MEDIANTE JAVASCRIPT ================ 54 | 55 | // let contenedor = document.getElementById("contenedor-siete"); 56 | // contenedor.className = "bg-blue"; 57 | 58 | //================ OBTENER/AGREGAR VALOR DE UN INPUT ================ 59 | 60 | // let inputCorreo = document.getElementById("inputCorreo"); 61 | // let inputContrasenia = document.getElementById("inputContrasenia"); 62 | 63 | // console.log(inputCorreo.value); 64 | // inputCorreo.value = "jesus@prueba.com"; 65 | // console.log(inputCorreo.value); 66 | 67 | // console.log(inputContrasenia.value); 68 | 69 | //================ EJEMPLO COMPLETO ================ 70 | 71 | const listaProductos = [ 72 | { 73 | id: 1, 74 | nombre: "Laptop", 75 | precioCompra: "800", 76 | precioVenta: "1100", 77 | cantidad: 2, 78 | }, 79 | { 80 | id: 2, 81 | nombre: "PC", 82 | precioCompra: "900", 83 | precioVenta: "1500", 84 | cantidad: 3, 85 | }, 86 | { 87 | id: 3, 88 | nombre: "Impresora", 89 | precioCompra: "500", 90 | precioVenta: "800", 91 | cantidad: 5, 92 | }, 93 | { id: 4, nombre: "USB", precioCompra: "25", precioVenta: "30", cantidad: 50 }, 94 | ]; 95 | 96 | const contenedorProductos = document.getElementById("contenedor-productos"); 97 | 98 | for (const producto of listaProductos) { 99 | let column = document.createElement("div"); 100 | column.className = "col-md-4 mt-3 "; 101 | column.id = `columna-${producto.id}`; 102 | column.innerHTML = ` 103 |
104 |
105 |

Nombre: ${producto.nombre}

106 |

Precio compra: ${producto.precioCompra}

107 |

Precio venta: ${producto.precioVenta}

108 |

Cantidad: ${producto.cantidad}

109 |
110 |
`; 111 | 112 | contenedorProductos.append(column); 113 | } 114 | /* 115 | let columnaBorrar = document.getElementById("columna-1") 116 | 117 | columnaBorrar.remove() 118 | */ 119 | -------------------------------------------------------------------------------- /Clase 8 (DOM)/styles.css: -------------------------------------------------------------------------------- 1 | .bg-blue{ 2 | background-color: aquamarine; 3 | } -------------------------------------------------------------------------------- /Clase 9 (Eventos)/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 14 | 15 | 16 | 59 |
60 |
61 |
62 |
63 |
64 |
65 |

Ejemplo formulario

66 |
67 |
68 | 69 | 70 |
71 |
72 | 73 | 78 |
79 | 80 |
81 | 82 | 87 |
88 | 89 |
90 | 91 | 92 |
93 | 94 |
95 | 96 | 97 |
98 | 99 |
100 | 101 |
102 |
103 |
104 |
105 |
106 | 111 | 112 | 113 | 114 | -------------------------------------------------------------------------------- /Clase 9 (Eventos)/index.js: -------------------------------------------------------------------------------- 1 | //================ EVENTO CLICK ================ 2 | // let botonUno = document.getElementById("btnEventoUno") 3 | // let botonDos = document.getElementById("btnEventoDos") 4 | 5 | // botonUno.addEventListener("click", () => { 6 | // alert("Se oprimió el boton uno") 7 | // }) 8 | 9 | // botonDos.onclick = () => { 10 | // alert("Se oprimió el botón dos") 11 | // } 12 | 13 | // function mostrarAlert(){ 14 | // alert("Se oprimió el botón tres") 15 | // } 16 | 17 | //================ EVENTO GENERALES EN BOTONES ================ 18 | 19 | // let boton = document.getElementById("boton") 20 | 21 | // boton.onmousedown = () => { 22 | // console.log("Evento mouse down") 23 | // } 24 | 25 | // boton.onmouseup = () => { 26 | // console.log("Evento mouse up") 27 | // } 28 | 29 | // boton.onmouseover = () => { 30 | // console.log("Evento mouse over") 31 | // } 32 | 33 | // boton.onmouseout = () => { 34 | // console.log("Evento mouse out") 35 | // } 36 | 37 | // boton.onmousemove = () => { 38 | // console.log("Evento mouse move") 39 | // } 40 | 41 | //================ EVENTO GENERALES EN INPUTS ================ 42 | 43 | // let inputNombre = document.getElementById("nombre"); 44 | // let inputEdad = document.getElementById("edad"); 45 | 46 | // inputNombre.onkeydown = () => { 47 | // alert("Se oprimió un boton, evento down") 48 | // } 49 | 50 | // inputNombre.onkeyup = () => { 51 | // alert("Se oprimió un boton, evento up") 52 | // } 53 | 54 | // inputNombre.onchange = () => { 55 | // console.log("se ejecuta evento onchange, input nombre"); 56 | // }; 57 | 58 | // inputEdad.onchange = () => { 59 | // console.log("se ejecuta evento onchange, input edad"); 60 | // }; 61 | 62 | // inputNombre.oninput = () => { 63 | // console.log("se ejecuta evento oninput, input nombre"); 64 | // }; 65 | 66 | // inputEdad.oninput = () => { 67 | // console.log("se ejecuta evento oninput, input edad"); 68 | // }; 69 | 70 | //================ EVENTO SCROLL ================ 71 | 72 | // window.addEventListener("scroll", function (event) { 73 | // console.log(event, window.pageYOffset) 74 | // }); 75 | 76 | //================ EVENTO SUBMIT ================ 77 | 78 | // let miFormulario = document.getElementById("formulario"); 79 | // miFormulario.addEventListener("submit", validarFormulario); 80 | 81 | // function validarFormulario(e) { 82 | // e.preventDefault(); 83 | // console.log(e); 84 | // console.log("Formulario Enviado"); 85 | // } 86 | 87 | //================ EJEMPLO COMPLETO ================ 88 | 89 | let productos = []; 90 | 91 | let formulario; 92 | let inputId; 93 | let inputNombre; 94 | let inputPrecioCompra; 95 | let inputPrecioVenta; 96 | let inputCantidad; 97 | let contenedorProductos; 98 | 99 | class Producto { 100 | constructor(id, nombre, precioCompra, precioVenta, cantidad) { 101 | this.id = id; 102 | this.nombre = nombre.toUpperCase(); 103 | this.precioCompra = precioCompra; 104 | this.precioVenta = precioVenta; 105 | this.cantidad = cantidad; 106 | } 107 | calcularPrecioCompra = () => this.precioCompra * this.cantidad; 108 | calcularPrecioVenta = () => this.precioVenta * this.cantidad; 109 | } 110 | 111 | function inicializarElementos() { 112 | formulario = document.getElementById("formulario"); 113 | inputId = document.getElementById("inputId"); 114 | inputNombre = document.getElementById("inputNombreProducto"); 115 | inputPrecioCompra = document.getElementById("inputPrecioCompra"); 116 | inputPrecioVenta = document.getElementById("inputPrecioVenta"); 117 | inputCantidad = document.getElementById("inputCantidad"); 118 | contenedorProductos = document.getElementById("contenedorProductos"); 119 | } 120 | 121 | function inicializarEventos() { 122 | formulario.onsubmit = (event) => validarFormulario(event); 123 | } 124 | 125 | function validarFormulario(event) { 126 | event.preventDefault(); 127 | let idProducto = inputId.value; 128 | let nombre = inputNombre.value; 129 | let precioCompra = parseFloat(inputPrecioCompra.value); 130 | let precioVenta = parseFloat(inputPrecioVenta.value); 131 | let cantidad = parseInt(inputCantidad.value); 132 | 133 | const idExiste = productos.some((producto) => producto.id === idProducto); 134 | if (!idExiste) { 135 | let producto = new Producto( 136 | idProducto, 137 | nombre, 138 | precioCompra, 139 | precioVenta, 140 | cantidad 141 | ); 142 | 143 | productos.push(producto); 144 | formulario.reset(); 145 | 146 | pintarProductos(); 147 | } else { 148 | alert("El id ya existe"); 149 | } 150 | } 151 | 152 | function eliminarProducto(idProducto) { 153 | let columnaBorrar = document.getElementById(`columna-${idProducto}`); 154 | let indiceBorrar = productos.findIndex( 155 | (producto) => Number(producto.id) === Number(idProducto) 156 | ); 157 | 158 | productos.splice(indiceBorrar, 1); 159 | columnaBorrar.remove(); 160 | } 161 | 162 | function pintarProductos() { 163 | contenedorProductos.innerHTML = ""; 164 | productos.forEach((producto) => { 165 | let column = document.createElement("div"); 166 | column.className = "col-md-4 mt-3"; 167 | column.id = `columna-${producto.id}`; 168 | column.innerHTML = ` 169 |
170 |
171 |

ID: 172 | ${producto.id} 173 |

174 |

Nombre: 175 | ${producto.nombre} 176 |

177 |

Precio compra: 178 | ${producto.precioCompra} 179 |

180 |

Precio venta: 181 | ${producto.precioVenta} 182 |

183 |

Cantidad: 184 | ${producto.cantidad} 185 |

186 |
187 | 190 |
`; 191 | 192 | contenedorProductos.append(column); 193 | 194 | let botonEliminar = document.getElementById(`botonEliminar-${producto.id}`); 195 | botonEliminar.onclick = () => eliminarProducto(producto.id); 196 | }); 197 | } 198 | 199 | function main() { 200 | inicializarElementos(); 201 | inicializarEventos(); 202 | } 203 | 204 | main(); 205 | --------------------------------------------------------------------------------