├── .devcontainer └── devcontainer.json ├── .github └── workflows │ └── learnpack-audit.yml ├── .gitignore ├── .gitpod.Dockerfile ├── .gitpod.yml ├── .learn └── assets │ ├── a1mgdPD.gif │ ├── badge.svg │ └── js-events.jpeg ├── .vscode └── settings.json ├── README.es.md ├── README.md ├── badge.svg ├── exercises ├── 00-introduction │ ├── README.es.md │ └── README.md ├── 01-alert-on-click │ ├── README.es.md │ ├── README.md │ ├── index.html │ ├── index.js │ └── solution.hide.html ├── 02-on-click-Hello-World │ ├── README.es.md │ ├── README.md │ ├── index.html │ ├── index.js │ ├── solution.hide.html │ └── solution.hide.js ├── 03-sum-values │ ├── README.es.md │ ├── README.md │ ├── index.html │ ├── index.js │ └── solution.hide.js ├── 04-hide-on-click │ ├── README.es.md │ ├── README.md │ ├── index.html │ ├── index.js │ ├── solution.hide.js │ └── styles.css ├── 05-the-load-event │ ├── README.es.md │ ├── README.md │ ├── index.html │ ├── index.js │ ├── solution.hide.html │ └── solution.hide.js ├── 06-add-listener-with-js │ ├── README.es.md │ ├── README.md │ ├── index.html │ ├── index.js │ └── solution.hide.js ├── 07-count-on-click │ ├── README.es.md │ ├── README.md │ ├── index.html │ ├── index.js │ ├── solution.hide.html │ └── solution.hide.js ├── 07.1-change-turn-on-click │ ├── README.es.md │ ├── README.md │ ├── index.html │ ├── index.js │ └── solution.hide.js └── 08-event-target │ ├── README.es.md │ ├── README.md │ ├── index.html │ ├── index.js │ └── solution.hide.js └── learn.json /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | 2 | // For format details, see https://aka.ms/devcontainer.json. For config options, see the 3 | // README at: https://github.com/devcontainers/templates/tree/main/src/javascript-node 4 | { 5 | "name": "Node.js", 6 | // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile 7 | "image": "mcr.microsoft.com/devcontainers/javascript-node:0-16", 8 | "customizations": { 9 | "vscode": { 10 | "settings": { 11 | "editor.defaultFormatter": "esbenp.prettier-vscode", 12 | "workbench.editorAssociations": { 13 | "*.md": "vscode.markdown.preview.editor" 14 | } 15 | }, 16 | "extensions": ["learn-pack.learnpack-vscode"] 17 | } 18 | }, 19 | 20 | // Features to add to the dev container. More info: https://containers.dev/features. 21 | // "features": {}, 22 | 23 | // Use 'forwardPorts' to make a list of ports inside the container available locally. 24 | // "forwardPorts": [], 25 | "onCreateCommand": "npm i jest@29.7.0 jest-environment-jsdom@29.7.0 -g && npm i @learnpack/learnpack@5.0.29 -g && learnpack plugins:install @learnpack/dom@1.1.7" 26 | 27 | // Use 'postCreateCommand' to run commands after the container is created. 28 | // "postCreateCommand": "yarn install", 29 | 30 | // Configure tool-specific properties. 31 | // "customizations": {}, 32 | 33 | // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root. 34 | // "remoteUser": "root" 35 | } 36 | -------------------------------------------------------------------------------- /.github/workflows/learnpack-audit.yml: -------------------------------------------------------------------------------- 1 | # This workflow will do a clean install of node dependencies, cache/restore them, build the source code and run tests across different versions of node 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions 3 | 4 | name: Learnpack audit 5 | 6 | on: 7 | push: 8 | branches: [ main ] 9 | pull_request: 10 | branches: [ main ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | strategy: 18 | matrix: 19 | node-version: [20.x] 20 | # See supported Node.js release schedule at https://nodejs.org/en/about/releases/ 21 | 22 | steps: 23 | - uses: actions/checkout@v2 24 | - name: Use Node.js ${{ matrix.node-version }} 25 | uses: actions/setup-node@v2 26 | with: 27 | node-version: ${{ matrix.node-version }} 28 | - run: npm install @learnpack/learnpack@latest -g 29 | - run: learnpack audit -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore everything 2 | /* 3 | 4 | !.gitignore 5 | !.gitpod.yml 6 | !.gitpod.Dockerfile 7 | !learn.json 8 | !README.md 9 | !README.es.md 10 | !.vscode 11 | 12 | !/exercises 13 | !/exercises/* 14 | 15 | !/.learn 16 | /.learn/** 17 | !/.learn/resets 18 | !/.learn/resets/** 19 | !/.learn/assets 20 | !/.learn/assets/** 21 | 22 | *.pyc 23 | __pycache__/ 24 | .pytest_cache/ 25 | -------------------------------------------------------------------------------- /.gitpod.Dockerfile: -------------------------------------------------------------------------------- 1 | FROM gitpod/workspace-full:latest 2 | 3 | USER gitpod 4 | 5 | RUN npm i jest@29.7.0 jest-environment-jsdom@29.7.0 -g 6 | RUN npm i @learnpack/learnpack@2.1.50 -g && learnpack plugins:install @learnpack/dom@1.1.7 7 | -------------------------------------------------------------------------------- /.gitpod.yml: -------------------------------------------------------------------------------- 1 | 2 | image: 3 | file: .gitpod.Dockerfile 4 | 5 | ports: 6 | - port: 3000 7 | onOpen: ignore 8 | 9 | vscode: 10 | extensions: 11 | - learn-pack.learnpack-vscode 12 | github: 13 | prebuilds: 14 | # enable for the master/default branch (defaults to true) 15 | master: true 16 | # enable for pull requests coming from this repo (defaults to true) 17 | pullRequests: false 18 | # add a "Review in Gitpod" button as a comment to pull requests (defaults to true) 19 | addComment: false 20 | -------------------------------------------------------------------------------- /.learn/assets/a1mgdPD.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/4GeeksAcademy/javascript-events-tutorial-exercises/0ea8b41d41eaa16382b9b1b3898f6d8f2071f14f/.learn/assets/a1mgdPD.gif -------------------------------------------------------------------------------- /.learn/assets/badge.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.learn/assets/js-events.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/4GeeksAcademy/javascript-events-tutorial-exercises/0ea8b41d41eaa16382b9b1b3898f6d8f2071f14f/.learn/assets/js-events.jpeg -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.autoSave": "afterDelay", 3 | "files.autoSaveDelay": 700, 4 | "editor.minimap.enabled": false, 5 | "workbench.editorAssociations": { 6 | "*.md": "vscode.markdown.preview.editor" 7 | } 8 | } -------------------------------------------------------------------------------- /README.es.md: -------------------------------------------------------------------------------- 1 | # Programación Orientada a Eventos con JavaScript 2 | 3 | 4 | 5 | > Por [@alesanchezr](https://twitter.com/alesanchezr) y [otros colaboradores](https://github.com/4GeeksAcademy/javascript-events-tutorial-exercises/graphs/contributors) en [4Geeks Academy](https://4geeksacademy.co/) 6 | 7 | ![last commit](https://img.shields.io/github/last-commit/4geeksacademy/javascript-arrays-exercises-tutorial) 8 | [![build by developers](https://img.shields.io/badge/build_by-Developers-blue)](https://breatheco.de) 9 | [![build by developers](https://img.shields.io/twitter/follow/4geeksacademy?style=social&logo=twitter)](https://twitter.com/4geeksacademy) 10 | 11 | Este tutorial es parte de un grupo de tutoriales sobre desarrollo web, este repositorio se enfoca solo en los Eventos de JavaScript. 12 | 13 | 14 | 15 | ### Aprenderás los siguientes conceptos: 16 | 17 | 1. Eventos del ratón. 18 | 2. Eventos del teclado. 19 | 3. Eventos de ventana. 20 | 4. Como reaccionar ante estos eventos para que tu aplicación web sea interactiva. 21 | 22 | 23 | ### Antes de empezar... hay otros tutoriales relacionados 24 | 25 | 1. [Introducción a HTML](https://github.com/4GeeksAcademy/html-tutorial-exercises-course) 26 | 2. [Introducción a CSS](https://github.com/4GeeksAcademy/css-tutorial-exercises-course) 27 | 3. [Introducción a JavaScript](https://github.com/4GeeksAcademy/javascript-beginner-exercises-tutorial) 28 | 4. [Introducción a El DOM](https://github.com/4GeeksAcademy/javascript-dom-tutorial-exercises) 29 | 5. [Uso de eventos & El DOM](https://github.com/4GeeksAcademy/javascript-events-tutorial-exercises) ← Estás aquí 🔥 30 | 6. [Programación Orientada a Objetos](https://github.com/4GeeksAcademy/object-oriented-javascript-tutorial-exercises) 31 | 32 | ## Instalación en un clic (recomendado) 33 | 34 | Puedes empezar estos ejercicios en pocos segundos haciendo clic en: [Abrir en Codespaces](https://codespaces.new/?repo=4GeeksAcademy/javascript-events-tutorial-exercises) (recomendado) o [Abrir en Gitpod](https://gitpod.io#https://github.com/4GeeksAcademy/javascript-events-tutorial-exercises.git). 35 | 36 | > Una vez ya tengas abierto VSCode los ejercicios de LearnPack deberían empezar automáticamente, si esto no sucede puedes intentar empezar los ejercicios escribiendo este comando en tu terminal: `$ learnpack start` 37 | 38 | ## Instalación local 39 | 40 | Clona el repositorio en tu ambiente local y sigue los siguientes pasos: 41 | 42 | 1) Asegúrate de tener instalado [LearnPack](https://github.com/learnpack/learnpack-cli), `node.js` versión v14+ y jest v27. Este es el comando para instalar learnpack-cli y jest: 43 | 44 | ```bash 45 | $ npm i learnpack jest@27.0.6 -g 46 | ``` 47 | 48 | 2) Clona o descarga este repositorio. Una vez que termines de descargar, encontrarás una nueva carpeta con un subdirectorio "exercises" que contiene todos los ejercicios dentro. 49 | 50 | 3) Instala el plugin de LearnPack para testear y compilar vanillajs: 51 | 52 | ```bash 53 | $ learnpack plugins:install learnpack-dom 54 | ``` 55 | 56 | 4) Inicializa el tutorial ejecutando el siguiente comando en la raíz del proyecto: 57 | 58 | ```bash 59 | $ learnpack start 60 | ``` 61 | 62 | 63 | 64 | 65 | ## ¿Cómo están organizados los ejercicios? 66 | 67 | Cada ejercicio es una pequeña aplicación de React que contiene los siguientes archivos: 68 | 69 | 1. **index.js:** representa el archivo JavaScript de entrada que se ejecutará cuando se cargue el sitio web. 70 | 1. **index.html:** representa la entrada HTML para el sitio web. 71 | 1. **style.css:** los estilos de tu sitio web, deben importarse desde index.html 72 | 2. **README.md:** contiene las instrucciones de los ejercicios. 73 | 3. **test.js:** no tienes que abrir este archivo, contiene el script de test para el ejercicio. 74 | 75 | > Nota: Estos ejercicios tienen calificación automática. Los tests son muy rígidos y estrictos, mi recomendación es que no prestes demasiada atención a los tests y los uses solo como una sugerencia o podrías frustrarte. 76 | 77 | ## Colaboradores 78 | 79 | Gracias a estas personas maravillosas ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): 80 | 81 | 1. [Alejandro Sanchez (alesanchezr)](https://github.com/alesanchezr), contribución: (programador) 💻, (idea) 🤔, (build-tests) ⚠️, (pull-request-review), 🤓 (build-tutorial), ✅ (documentación) 📖 82 | 83 | 2. [Paolo (plucodev)](https://github.com/plucodev), contribución: (bug reports) 🐛, (programador) 💻, (traducción) 🌎 84 | 85 | Este proyecto sigue la especificación [all-contributors](https://github.com/kentcdodds/all-contributors). ¡Todas las contribuciones son bienvenidas! 86 | 87 | Este y otros ejercicios son usados para [aprender a programar](https://4geeksacademy.com/es/aprender-a-programar/aprender-a-programar-desde-cero) por parte de los alumnos de 4Geeks Academy [Coding Bootcamp](https://4geeksacademy.com/us/coding-bootcamp) realizado por [Alejandro Sánchez](https://twitter.com/alesanchezr) y muchos otros contribuyentes. Conoce más sobre nuestros [Cursos de Programación](https://4geeksacademy.com/es/curso-de-programacion-desde-cero?lang=es) para convertirte en [Full Stack Developer](https://4geeksacademy.com/es/coding-bootcamps/desarrollador-full-stack/?lang=es), o nuestro [Data Science Bootcamp](https://4geeksacademy.com/es/coding-bootcamps/curso-datascience-machine-learning). 88 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Event-Oriented Programming with JavaScript 2 | 3 | 4 | 5 | 6 | > By [@alesanchezr](https://twitter.com/alesanchezr) and [other contributors](https://github.com/4GeeksAcademy/javascript-events-tutorial-exercises/graphs/contributors) at [4Geeks Academy](https://4geeksacademy.co/) 7 | 8 | ![last commit](https://img.shields.io/github/last-commit/4geeksacademy/javascript-arrays-exercises-tutorial) 9 | [![build by developers](https://img.shields.io/badge/build_by-Developers-blue)](https://breatheco.de) 10 | [![build by developers](https://img.shields.io/twitter/follow/4geeksacademy?style=social&logo=twitter)](https://twitter.com/4geeksacademy) 11 | 12 | This tutorial is part of a bigger group of tutorials about web development, this repository focuses only on JavaScript Events, you will learn Mouse Events, Keyboard events, Frame Events and how to react to those events to make your web application interactive. 13 | 14 | *Estas instrucciones [están disponibles en 🇪🇸 español](https://github.com/4GeeksAcademy/javascript-events-tutorial-exercises/blob/master/README.es.md) :es:* 15 | 16 | 17 | 18 | ### What you will learn during this tutorial: 19 | 20 | 1. The first event that triggers on a website. 21 | 2. Make your code react to user clicks on buttons. 22 | 3. Create a counter that increases when the user clicks. 23 | 4. Add event listeners. 24 | 5. What is the event target? 25 | 26 | 27 | ### Before we start... other related tutorials 28 | 29 | 1. [Introduction to HTML](https://github.com/4GeeksAcademy/html-tutorial-exercises-course) 30 | 2. [Introduction to CSS](https://github.com/4GeeksAcademy/css-tutorial-exercises-course) 31 | 3. [Introduction to JavaScript](https://github.com/4GeeksAcademy/javascript-beginner-exercises-tutorial) 32 | 4. [Introduction to The DOM](https://github.com/4GeeksAcademy/javascript-dom-tutorial-exercises) 33 | 5. [Using events & The DOM](https://github.com/4GeeksAcademy/javascript-events-tutorial-exercises) ← You are here now 🔥 34 | 6. [Object Oriented Programming](https://github.com/4GeeksAcademy/object-oriented-javascript-tutorial-exercises) 35 | 36 | ## One click installation (recommended): 37 | 38 | You can open these exercises in just a few seconds by clicking: [Open in Codespaces](https://codespaces.new/?repo=4GeeksAcademy/javascript-events-tutorial-exercises) (recommended) or [Open in Gitpod](https://gitpod.io#https://github.com/4GeeksAcademy/javascript-events-tutorial-exercises). 39 | 40 | > Once you have VSCode open, the LearnPack exercises should start automatically. If exercises don't run automatically you can try typing on your terminal: `$ learnpack start` 41 | 42 | ## Local Installation 43 | 44 | Clone the repository in your local environment and follow the steps below: 45 | 46 | 1) Make sure you have [LearnPack](https://github.com/learnpack/learnpack-cli), `node.js` version v14+, and jest v27 installed. This is the command to install the learnpack-cli and jest: 47 | 48 | ```bash 49 | $ npm i learnpack jest@29.7.0 jest-environment-jsdom@29.7.0 -g 50 | ``` 51 | 52 | 2) Clone or download this repository. Once you finish downloading, you will find a new folder with a subdirectory "exercises" that contains all the exercises within. 53 | 54 | 3) Install the LearnPack plugin to test and compile vanillajs: 55 | 56 | ```bash 57 | $ learnpack plugins:install @learnpack/dom 58 | ``` 59 | 60 | 4) Start the tutorial/exercises by running the following command from the root of the project: 61 | 62 | ```bash 63 | $ learnpack start 64 | ``` 65 | 66 | 67 | 68 | 69 | ## How are the exercises organized? 70 | 71 | Each exercise is a small React application containing the following files: 72 | 73 | 1. **index.js:** represents the entry JavaScript file that will be executed by the computer. 74 | 1. **index.html:** represents the entry website. 75 | 1. **style.css:** your website styles, they have to be imported from the index.html. 76 | 2. **README.md:** contains exercise instructions. 77 | 3. **test.js:** you don't have to open this file, it contains the testing script for the exercise. 78 | 79 | > Note: The exercises have automatic grading, but it's very rigid and strict, my recommendation is to not take the tests too serious and use them only as a suggestion, or you may get frustrated. 80 | 81 | ## Contributors 82 | 83 | Thanks goes to these wonderful people ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): 84 | 85 | 1. [Alejandro Sanchez (alesanchezr)](https://github.com/alesanchezr), contribution: (coder) 💻, (idea) 🤔, (build-tests) ⚠️, (pull-request-review) 👀, (build-tutorial) ✅, (documentation) 📖 86 | 87 | 2. [Paolo (plucodev)](https://github.com/plucodev), contribution: (bug reports) 🐛, (coder) 💻, (translation) 🌎 88 | 89 | This project follows the [all-contributors](https://github.com/kentcdodds/all-contributors) specification. Contributions of any kind are welcome! 90 | 91 | This and many other exercises are built by students as part of the 4Geeks Academy [Coding Bootcamp](https://4geeksacademy.com/us/coding-bootcamp) by [Alejandro Sánchez](https://twitter.com/alesanchezr) and many other contributors. Find out more about our [Full Stack Developer Course](https://4geeksacademy.com/us/coding-bootcamps/part-time-full-stack-developer), and [Data Science Bootcamp](https://4geeksacademy.com/us/coding-bootcamps/datascience-machine-learning). 92 | -------------------------------------------------------------------------------- /exercises/00-introduction/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | intro: "https://www.youtube.com/watch?v=TbciSCu2kFQ" 3 | --- 4 | 5 | # ¡Bienvenido a Eventos de JavaScript! 6 | 7 | En este tutorial estaremos viendo los eventos de JavaScript: 8 | 9 | 1. Evento onClick. 10 | 11 | 2. Obtener valores de objetivos de eventos (event targets). 12 | 13 | 3. Cambiar propiedades de CSS con JavaScript cuando suceda algún evento. 14 | 15 | 4. Esperar a que el sitio web CARGUE(LOAD) antes de hacer nada (evento `onLoad`). 16 | 17 | 5. Implementar un contador simple cuando el usuario haga clic. 18 | -------------------------------------------------------------------------------- /exercises/00-introduction/README.md: -------------------------------------------------------------------------------- 1 | # Welcome to JavaScript Events! 2 | 3 | During this tutorial, we are going to go over JavaScript Events: 4 | 5 | 1. onClick event. 6 | 7 | 2. Get values from event targets. 8 | 9 | 3. Change CSS properties with JavaScript when events trigger. 10 | 11 | 4. Waiting for the website to LOAD before doing anything (`onLoad` event). 12 | 13 | 5. Implementing a simple counter when the user clicks. 14 | -------------------------------------------------------------------------------- /exercises/01-alert-on-click/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=5L0_li8L16E" 3 | --- 4 | 5 | # `01` Alert onclick 6 | 7 | Puedes establecer funciones de Event Listener para manejar cualquier tipo de eventos ¡La lista de eventos posibles es inmensa! Click, Double Click, Mouseover, Load, Print, etc... 8 | 9 | En este código HTML hay 2 botones: uno tiene la función `myClickFunction` como listener de evento asignada al evento clic usando el evento `onclick`. 10 | 11 | ## 📝 Instrucciones: 12 | 13 | 1. Añade la misma función como listener de evento al evento clic en el `#button2`. 14 | 15 | ## 💡 Pista: 16 | 17 | + Usa la propiedad de la etiqueta llamada "onclick" igual que en el otro botón. 18 | 19 | -------------------------------------------------------------------------------- /exercises/01-alert-on-click/README.md: -------------------------------------------------------------------------------- 1 | # `01` Alert onclick 2 | 3 | You can set Event Listener functions to handle any kind of events. The list of possible events is huge! Click, Double Click, Mouseover, Load, Print, etc... 4 | 5 | In this HTML code there are 2 buttons: one of them has `myClickFunction` as a listener assigned to the click event using the `onclick` event. 6 | 7 | ## 📝 Instructions: 8 | 9 | 1. Add that same function as an Event Listener to the click event in `#button2`. 10 | 11 | ## 💡 Hint: 12 | 13 | + Use the tag property called "onclick" just like in the other button. 14 | -------------------------------------------------------------------------------- /exercises/01-alert-on-click/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 4Geeks Academy 7 | 8 | 9 | 10 | and 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /exercises/01-alert-on-click/index.js: -------------------------------------------------------------------------------- 1 | window.myClickFunction = function myClickFunction() { 2 | alert("Your first function!"); 3 | }; 4 | -------------------------------------------------------------------------------- /exercises/01-alert-on-click/solution.hide.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 4Geeks Academy 7 | 8 | 9 | 10 | and 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /exercises/02-on-click-Hello-World/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=fFNighEUZuE" 3 | --- 4 | 5 | # `02` onclick Hello World 6 | 7 | ## 📝 Instrucciones: 8 | 9 | 1. Crea una función Listener de evento que sea llamada automáticamente cuando el usuario presione el botón que está en el archivo HTML del ejercicio. 10 | 11 | ## 💡 Pistas: 12 | 13 | - Usa la propiedad `onclick` de la etiqueta input. 14 | 15 | - Declara la función JavaScript en el `index.js` y establécela como listener en la propiedad input. 16 | -------------------------------------------------------------------------------- /exercises/02-on-click-Hello-World/README.md: -------------------------------------------------------------------------------- 1 | # `02` onclick Hello World 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Create an Event Listener function that will be automatically called when the user presses the button that is on the HTML side of the exercise. 6 | 7 | ## 💡 Hints: 8 | 9 | - Use the `onclick` property of the input tag. 10 | 11 | - Declare the JavaScript function in `index.js` and set it as a listener in the input property. 12 | -------------------------------------------------------------------------------- /exercises/02-on-click-Hello-World/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 4Geeks Academy 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /exercises/02-on-click-Hello-World/index.js: -------------------------------------------------------------------------------- 1 | // Declare your function here 2 | -------------------------------------------------------------------------------- /exercises/02-on-click-Hello-World/solution.hide.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 4Geeks Academy 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /exercises/02-on-click-Hello-World/solution.hide.js: -------------------------------------------------------------------------------- 1 | // Declare your function here 2 | window.myClickFunction = function myClickFunction() { 3 | alert("Hello World"); 4 | }; 5 | -------------------------------------------------------------------------------- /exercises/03-sum-values/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=qoax-ggb740" 3 | --- 4 | 5 | # `03` Sum Values 6 | 7 | ## 📝 Instrucciones: 8 | 9 | 1. Completa la función `calculateSumListener` con el código necesario para imprimir la suma de los valores de los primeros dos input con el tercero. 10 | 11 | ## 💡 Pista: 12 | 13 | + Cuando obtienes el valor de un input, se recomienda convertir el valor a un número entero con la función `parseInt`. De esa forma te aseguras de que el resultado de 2 + 2 sea `4`, en vez de `22`. Si estas obteniendo `22` como resultado, significa que el valor del input esta siendo tratado como un string en vez de un número entero. 14 | -------------------------------------------------------------------------------- /exercises/03-sum-values/README.md: -------------------------------------------------------------------------------- 1 | # `03` Sum Values 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Fill the `calculateSumListener` function with the code needed to print the sum of the values of the first two inputs into the third one. 6 | 7 | ## 💡 Hint: 8 | 9 | + When you get the value of an input, it is recommended to parse the value as an integer with the function `parseInt`. That way you make sure that the result of 2 + 2 is `4`, instead of `22`. If you are getting `22` as a result, it means that the value of the input is being treated as strings instead of integers. 10 | -------------------------------------------------------------------------------- /exercises/03-sum-values/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 4Geeks Academy 7 | 8 | 9 | 10 | + = 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /exercises/03-sum-values/index.js: -------------------------------------------------------------------------------- 1 | // Adding the function to the window makes it globally available 2 | window.calculateSumListener = function() { 3 | // Return the value of the input #firstNumber 4 | let stringA = document.getElementById("firstNumber").value; 5 | // Return the value of the input #secondNumber 6 | let stringB = document.getElementById("secondNumber").value; 7 | // Your code here 8 | 9 | }; 10 | -------------------------------------------------------------------------------- /exercises/03-sum-values/solution.hide.js: -------------------------------------------------------------------------------- 1 | // Adding the function to the window makes it globally available 2 | window.calculateSumListener = function() { 3 | // Return the value of the input #firstNumber 4 | let stringA = document.getElementById("firstNumber").value; 5 | // Return the value of the input #secondNumber 6 | let stringB = document.getElementById("secondNumber").value; 7 | // Your code here 8 | let sum = parseInt(stringA) + parseInt(stringB); 9 | let resultInput = document.getElementById("resultNumber"); 10 | resultInput.value = sum; 11 | }; 12 | -------------------------------------------------------------------------------- /exercises/04-hide-on-click/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=_bjCwo4ptBw" 3 | --- 4 | 5 | # `04` Hide onclick 6 | 7 | ## 📝 Instrucciones: 8 | 9 | 1. Completa la función `myEventListener` con el código necesario para ocultar el primer `div` del documento. 10 | 11 | 12 | ## 💡 Pista: 13 | 14 | + Para ocultar un elemento con JavaScript debes usar `element.style.display`, y establece el valor correcto. 15 | -------------------------------------------------------------------------------- /exercises/04-hide-on-click/README.md: -------------------------------------------------------------------------------- 1 | # `04` Hide onclick 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Fill the `myEventListener` function with the code needed to hide the first `div` of the document. 6 | 7 | ## 💡 Hint: 8 | 9 | + To hide an element with JavaScript you need to do `element.style.display`, then set it with the correct value. 10 | -------------------------------------------------------------------------------- /exercises/04-hide-on-click/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 4Geeks Academy 8 | 9 | 10 | 11 | 12 |
13 | My first div 14 |
15 |
16 | My second div 17 |
18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /exercises/04-hide-on-click/index.js: -------------------------------------------------------------------------------- 1 | window.myEventListener = function myEventListener() { 2 | // Your code here 3 | 4 | } 5 | -------------------------------------------------------------------------------- /exercises/04-hide-on-click/solution.hide.js: -------------------------------------------------------------------------------- 1 | window.myEventListener = function myEventListener() { 2 | // Your code here 3 | let firstDiv = document.querySelector('#firstDiv') 4 | firstDiv.style.display = "none" 5 | } 6 | -------------------------------------------------------------------------------- /exercises/04-hide-on-click/styles.css: -------------------------------------------------------------------------------- 1 | #firstDiv { 2 | background: green; 3 | } 4 | #secondDiv { 5 | background: yellow; 6 | } 7 | -------------------------------------------------------------------------------- /exercises/05-the-load-event/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=1P3i4ea4WfI" 3 | --- 4 | 5 | # `05` The load Event 6 | 7 | Es una muy buena práctica esperar a que el navegador termine de cargar la página antes de iniciar el flujo de tu sitio web/aplicación, para hacerlo, usamos el evento LOAD. 8 | 9 | ## 📝 Instrucciones: 10 | 11 | 1. Crea una función llamada `loadListener` que escuche al evento `load` y luego muestre una alerta con el string "Loading finished..." cuando se la llame. 12 | 13 | ## 💡 Pistas: 14 | 15 | - El listener debe asignarse al body. 16 | 17 | - Así se añade un listener de evento a un evento load: http://www.w3schools.com/jsref/event_onload.asp 18 | -------------------------------------------------------------------------------- /exercises/05-the-load-event/README.md: -------------------------------------------------------------------------------- 1 | # `05` The load Event 2 | 3 | It is a very good practice to wait for the browser to finish loading the page before starting the flow of your website/application, to do so, we use the LOAD event. 4 | 5 | ## 📝 Instructions: 6 | 7 | 1. Create a function called `loadListener` that listens to the `load` event and triggers an alert with the string "Loading finished..." when called. 8 | 9 | ## 💡 Hints: 10 | 11 | - The listener has to be assigned to the body. 12 | 13 | - Here is how to add the event listener to the load event: http://www.w3schools.com/jsref/event_onload.asp 14 | -------------------------------------------------------------------------------- /exercises/05-the-load-event/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 4Geeks Academy 7 | 8 | 9 | 10 |

Hello! Please alert "Loading finished..." when this website finally loads.

11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /exercises/05-the-load-event/index.js: -------------------------------------------------------------------------------- 1 | // Your function goes here 2 | -------------------------------------------------------------------------------- /exercises/05-the-load-event/solution.hide.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 4Geeks Academy 7 | 8 | 9 | 10 |

Hello! Please alert "Loading finished..." when this website finally loads.

11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /exercises/05-the-load-event/solution.hide.js: -------------------------------------------------------------------------------- 1 | // Your function goes here 2 | function loadListener() { 3 | alert("Loading finished...") 4 | } 5 | -------------------------------------------------------------------------------- /exercises/06-add-listener-with-js/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=aIZsIz09GcY" 3 | --- 4 | 5 | # `06` Add Listener With JS 6 | 7 | A veces debemos añadir listener de eventos DURANTE EL TIEMPO DE EJECUCIÓN. 8 | 9 | La mejor forma de hacer eso es usando una función `addEventListener` a cualquier elemento del DOM que queramos empezar a escuchar. 10 | 11 | ## 📝 Instrucciones: 12 | 13 | Ahora mismo, el código está escuchando la ejecución y muestra una alerta cuando el sitio web termina de cargar. 14 | 15 | 1. Escribe el código necesario para que se muestre una alerta que diga "woohoo!" cada vez que le des clic al botón verde. 16 | 17 | ## 💡 Pistas: 18 | 19 | - Aquí está la documentación para añadir un listener de evento(addEventListener): https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener 20 | 21 | - Usa la función `alert()`. 22 | 23 | ## 💻 Resultado esperado: 24 | 25 | ![06-add-listener-with-js](../../.learn/assets/a1mgdPD.gif?raw=true) 26 | -------------------------------------------------------------------------------- /exercises/06-add-listener-with-js/README.md: -------------------------------------------------------------------------------- 1 | # `06` Add Listener With JS 2 | 3 | Sometimes we need to add event listeners DURING RUNTIME. 4 | 5 | The best way to do that is using the `addEventListener` function on any DOM element that we want to start listening to. 6 | 7 | ## 📝 Instructions: 8 | 9 | Right now, this code is listening for the load, and it prompts an alert when the website finishes loading. 10 | 11 | 1. Write the necessary code to alert "woohoo!" whenever the green button is clicked. 12 | 13 | ## 💡 Hints: 14 | 15 | - Here is the documentation for addEventListener: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener 16 | 17 | - Use the function `alert()`. 18 | 19 | ## 💻 Expected result: 20 | 21 | ![06-add-listener-with-js](../../.learn/assets/a1mgdPD.gif?raw=true) 22 | -------------------------------------------------------------------------------- /exercises/06-add-listener-with-js/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 4Geeks Academy 7 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /exercises/06-add-listener-with-js/index.js: -------------------------------------------------------------------------------- 1 | window.onload = function myLoadFunction() { 2 | alert("The website just finished loading!"); 3 | // Some code here 4 | 5 | }; 6 | 7 | // The listener function here 8 | -------------------------------------------------------------------------------- /exercises/06-add-listener-with-js/solution.hide.js: -------------------------------------------------------------------------------- 1 | window.onload = function myLoadFunction() { 2 | alert("The website just finished loading!"); 3 | // Some code here 4 | const greenButton = document.getElementById("theGreen"); 5 | greenButton.addEventListener("click", myClickFunction); 6 | }; 7 | 8 | // The listener function here 9 | function myClickFunction() { 10 | alert("woohoo!"); 11 | }; 12 | -------------------------------------------------------------------------------- /exercises/07-count-on-click/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=AtGZsioWZ14" 3 | --- 4 | 5 | # `07` Count onclick 6 | 7 | Si tienes **variables globales**, puedes cambiar su valor durante el tiempo de ejecución usando los handlers de eventos. Por ejemplo, este código incrementa el valor de la variable `counter` cada vez que el usuario hace clic en el botón **Increase**. 8 | 9 | ```js 10 | window.increaseCounter = function increaseCounter() { 11 | counter++; 12 | } 13 | ``` 14 | 15 | ## 📝 Instrucciones: 16 | 17 | 1. Crea un botón que disminuya con una función handler de evento. La función debería disminuir la variable `counter` y actualizar el número en pantalla. 18 | -------------------------------------------------------------------------------- /exercises/07-count-on-click/README.md: -------------------------------------------------------------------------------- 1 | # `07` Count onclick 2 | 3 | If you have global variables, you can change their value during runtime using event handlers. For example, this code is increasing the value of the `counter` variable every time the user clicks on the **Increase** button. 4 | 5 | ```js 6 | window.increaseCounter = function increaseCounter() { 7 | counter++; 8 | } 9 | ``` 10 | 11 | ## 📝 Instructions: 12 | 13 | 1. Create a decrease button with an event handler function. The function should decrease the `counter` variable and update the number on screen. 14 | -------------------------------------------------------------------------------- /exercises/07-count-on-click/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 4Geeks Academy 8 | 9 | 10 | 11 |

Loading...

12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /exercises/07-count-on-click/index.js: -------------------------------------------------------------------------------- 1 | // This is a global variable 2 | let counter = 0; 3 | 4 | window.onload = function loadFunction() 5 | { 6 | // Here I set the screen to the initial value when the website is fully loaded 7 | document.getElementById('screen').innerHTML = "The counter value is "+counter; 8 | } 9 | 10 | // Called when the user clicks 11 | window.increaseCounter = function increaseCounter() 12 | { 13 | // Increase the global counter by one 14 | counter++; 15 | // Update the screen with the new value 16 | document.getElementById('screen').innerHTML = "The counter value is "+counter; 17 | } 18 | 19 | // Your code here 20 | 21 | -------------------------------------------------------------------------------- /exercises/07-count-on-click/solution.hide.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 4Geeks Academy 7 | 8 | 9 | 10 |

Loading...

11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /exercises/07-count-on-click/solution.hide.js: -------------------------------------------------------------------------------- 1 | // This is a global variable 2 | let counter = 0; 3 | 4 | window.onload = function loadFunction() 5 | { 6 | // Here I set the screen to the initial value when the website is fully loaded 7 | document.getElementById('screen').innerHTML = "The counter value is "+counter; 8 | } 9 | 10 | // Called when the user clicks 11 | window.increaseCounter = function increaseCounter() 12 | { 13 | // Increase the global counter by one 14 | counter++; 15 | // Update the screen with the new value 16 | document.getElementById('screen').innerHTML = "The counter value is "+counter; 17 | } 18 | 19 | // Your code here 20 | window.decreaseCounter = function decreaseCounter() 21 | { 22 | // Decrease the global counter by one 23 | counter--; 24 | // Update the screen with the new value 25 | document.getElementById('screen').innerHTML = "The counter value is "+counter; 26 | } 27 | -------------------------------------------------------------------------------- /exercises/07.1-change-turn-on-click/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=XUGMHH4RaOY" 3 | --- 4 | 5 | # `07.1` Change Turn on Click 6 | 7 | Digamos que quieres crear una herramienta para cambiar de turno entre dos jugadores: Mario y Juan. 8 | 9 | Para eso hemos creado la variable global `currentUser` (jugador actual) y guardado el nombre del jugador actual en esa variable. Cada vez que haces clic en el botón, la variable cambia su valor a la del otro jugador. 10 | 11 | ## 📝 Instrucciones: 12 | 13 | 1. Cambia el código de la función `turnChanger` para añadir un tercer jugador llamado "Josh". 14 | 15 | ## 💡 Pista: 16 | 17 | + Añade una condición `else if` ya sea para Juan o Josh y cambia el valor de la variable `currentUser` consecuentemente. 18 | -------------------------------------------------------------------------------- /exercises/07.1-change-turn-on-click/README.md: -------------------------------------------------------------------------------- 1 | # `07.1` Change Turn on Click 2 | 3 | Let's say that you want to create a turn-changer tool to switch turns between two players: Mario and Juan. 4 | 5 | For that, we have created the global variable `currentUser` and stored the current player name in that variable, then updated the value of that variable every time the button is clicked to the other player's name. 6 | 7 | ## 📝 Instructions: 8 | 9 | 1. Change the code of the `turnChanger` function to add a third player called "Josh" 10 | 11 | ## 💡 Hint: 12 | 13 | + Add an `else if` condition asking for either Juan or Josh and change the value of `currentUser` variable accordingly. 14 | -------------------------------------------------------------------------------- /exercises/07.1-change-turn-on-click/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 4Geeks Academy 7 | 8 | 9 |

Loading...

10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /exercises/07.1-change-turn-on-click/index.js: -------------------------------------------------------------------------------- 1 | let currentUser = "Mario"; 2 | 3 | window.onload = function loadfn() { 4 | document.getElementById("screen").innerHTML = "It's " + currentUser + "'s turn"; 5 | } 6 | 7 | // Modify this function 8 | window.turnChanger = function turnChanger() { 9 | if (currentUser == "Mario") { 10 | currentUser = "Juan"; 11 | } else { 12 | currentUser = "Mario"; 13 | } 14 | 15 | document.getElementById("screen").innerHTML = "It's " + currentUser + "'s turn"; 16 | } 17 | -------------------------------------------------------------------------------- /exercises/07.1-change-turn-on-click/solution.hide.js: -------------------------------------------------------------------------------- 1 | let currentUser = "Mario"; 2 | 3 | window.onload = function loadfn() { 4 | document.getElementById("screen").innerHTML = "It's " + currentUser + "'s turn"; 5 | } 6 | 7 | // Modify this function 8 | window.turnChanger = function turnChanger() { 9 | if (currentUser == "Mario") { 10 | currentUser = "Juan"; 11 | } else if (currentUser == "Juan") { 12 | currentUser = "Josh"; 13 | } else { 14 | currentUser = "Mario"; 15 | } 16 | 17 | document.getElementById("screen").innerHTML = "It's " + currentUser + "'s turn"; 18 | } 19 | -------------------------------------------------------------------------------- /exercises/08-event-target/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=W4cQdQ574D4" 3 | --- 4 | 5 | # `08` Event Target 6 | 7 | Cada evento tiene información útil que puedes usar durante el tiempo de ejecución. 8 | 9 | Por ejemplo: 10 | 11 | - Si un usuario hace clic en un botón, sabes que botón específico tocó el usuario. 12 | 13 | - Si el usuario se desplaza por la ventana, puedes saber cuánto se ha desplazado. 14 | 15 | - Si el usuario movió el mouse, puedes saber la posición del mouse. 16 | 17 | - ¡Y mucho más! 18 | 19 | Cuando declaras una función event-handler, puedes usar un parámetro opcional que contenga la información del evento de esta manera: 20 | 21 | ```js 22 | function myFunctionName(eventInformation) {} 23 | ``` 24 | 25 | Este parámetro puede tener el nombre que quieras, y puedes estar seguro de que siempre contendrá la información del evento que lo activó. Por ejemplo, la propiedad `eventInformation.target` devolverá el objeto que activó el evento. 26 | 27 | ## 📝 Instrucciones: 28 | 29 | Este sitio web ya tiene un listener cuando se hace un clic en el `div` `#container`. 30 | 31 | 1. Por favor, muestra una alerta con el `id` del elemento objetivo (el elemento al cual se le hizo clic). 32 | 33 | ## 💡 Pista: 34 | 35 | + Aquí está la documentación sobre event.target: http://www.w3schools.com/jsref/event_target.asp 36 | -------------------------------------------------------------------------------- /exercises/08-event-target/README.md: -------------------------------------------------------------------------------- 1 | # `08` Event Target 2 | 3 | Every event has useful information that you can use during the runtime. 4 | 5 | For example: 6 | 7 | - If a user clicks on a button, you can know what specific button the user clicked. 8 | 9 | - If the window has scrolled, you can know how much the user has scrolled. 10 | 11 | - If the user moved the mouse, you can know the mouse position. 12 | 13 | - and much more! 14 | 15 | When you declare any event-handler function, you can use an optional parameter that contains the event information, like this: 16 | 17 | ```js 18 | function myFunctionName(eventInformation) {} 19 | ``` 20 | 21 | This parameter can have any name you want, and you can trust that it will always contain the information of the event that was triggered. For example the `eventInformation.target` property will return the object that triggered the event. 22 | 23 | ## 📝 Instructions: 24 | 25 | This website already has a listener for the click on the `#container` `div`. 26 | 27 | 1. Please prompt an alert with the `id` of the target element (the element that was clicked). 28 | 29 | ## 💡 Hint: 30 | 31 | + Here is the documentation on the event.target: http://www.w3schools.com/jsref/event_target.asp 32 | -------------------------------------------------------------------------------- /exercises/08-event-target/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 4Geeks Academy 7 | 8 | 9 |
10 | 11 | Click me 12 | 13 | 14 |
15 | 16 | 17 | -------------------------------------------------------------------------------- /exercises/08-event-target/index.js: -------------------------------------------------------------------------------- 1 | window.onload = function loadFn() { 2 | let containerElm = document.getElementById("container"); 3 | containerElm.addEventListener("click", function(event) { 4 | // Your code here 5 | 6 | }); 7 | }; 8 | -------------------------------------------------------------------------------- /exercises/08-event-target/solution.hide.js: -------------------------------------------------------------------------------- 1 | window.onload = function loadFn() { 2 | let containerElm = document.getElementById("container"); 3 | containerElm.addEventListener("click", function(event) { 4 | // Your code here 5 | alert(event.target.id); 6 | }); 7 | }; 8 | -------------------------------------------------------------------------------- /learn.json: -------------------------------------------------------------------------------- 1 | { 2 | "language": "vanillajs", 3 | "difficulty": "beginner", 4 | "preview": "https://github.com/4GeeksAcademy/javascript-events-tutorial-exercises/blob/master/.learn/assets/js-events.jpeg?raw=true", 5 | "duration": 8, 6 | "repository": "https://github.com/4GeeksAcademy/javascript-events-tutorial-exercises", 7 | "description": { 8 | "us": "Master JavaScript Events: Learn to make your application interactive by handling user actions like clicks, keyboard input, mouse movement, and window resizing. Explore onClick events, dynamically change CSS, retrieve event target values, and implement features like counters and onLoad actions.", 9 | "es": "Domina los eventos de JavaScript: Aprende a hacer que tu aplicación sea interactiva manejando acciones del usuario como clics, entrada del teclado, movimiento del mouse y cambios de tamaño de la ventana. Explora eventos onClick, cambia dinámicamente el CSS, obtén valores de objetivos de eventos e implementa funciones como contadores y acciones onLoad." 10 | }, 11 | "title": { 12 | "us": "Javascript Events", 13 | "es": "Eventos de Javascript" 14 | }, 15 | "slug": "javascript-events", 16 | "projectType": "tutorial", 17 | "videoSolutions": false, 18 | "gitpod": true, 19 | "bugsLink": "https://github.com/learnpack/learnpack/issues/new", 20 | "disableGrading": true, 21 | "editor": { 22 | "version": "5.0", 23 | "agent": "vscode" 24 | }, 25 | "telemetry": { 26 | "batch": "https://breathecode.herokuapp.com/v1/assignment/me/telemetry?asset_id=152" 27 | } 28 | 29 | } 30 | --------------------------------------------------------------------------------