folder names
17
3-terrarium/1-intro-to-html/.github/post-lecture-quiz.md
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
*Complete this quiz after the lesson by checking one answer per question.*
|
||||
|
||||
1. [Spans and Divs are interchangeable]
|
||||
|
||||
- [ ] [true]
|
||||
- [ ] [false]
|
||||
|
||||
2. [The head of an HTML doc can contain:]
|
||||
|
||||
- [ ] [the title tag]
|
||||
- [ ] [metadata]
|
||||
- [ ] [all the above]
|
||||
|
||||
3. [You can't use deprecated tags in your markup]
|
||||
- [ ] [true]
|
||||
- [ ] [false]
|
||||
- [ ] [false, but they have been deprecated for good reason]
|
19
3-terrarium/1-intro-to-html/.github/pre-lecture-quiz.md
vendored
Normal file
@@ -0,0 +1,19 @@
|
||||
*A warm-up quiz about HTML*
|
||||
|
||||
Complete this quiz in class
|
||||
|
||||
1. HTML stands for 'HyperText Mockup Language'
|
||||
|
||||
- [ ] [true]
|
||||
- [ ] [false]
|
||||
|
||||
2. All HTML tags need both opening and closing tags
|
||||
|
||||
- [ ] [true]
|
||||
- [ ] [false]
|
||||
|
||||
3. Using semantic markup is most important for
|
||||
|
||||
- [ ] [code readability]
|
||||
- [ ] [screen readers]
|
||||
- [ ] [maintenance]
|
21
3-terrarium/1-intro-to-html/LICENSE
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2020 WebDev-For-Beginners
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
219
3-terrarium/1-intro-to-html/README.md
Normal file
@@ -0,0 +1,219 @@
|
||||
# Terrarium Project Part 1: Introduction to HTML
|
||||
|
||||

|
||||
> Sketchnote by [Tomomi Imura](https://twitter.com/girlie_mac)
|
||||
|
||||
## [Pre-lecture quiz](.github/pre-lecture-quiz.md)
|
||||
|
||||
### Introduction:
|
||||
|
||||
HTML, or HyperText Markup Language, is the 'skeleton' of the web. If CSS 'dresses up' your HTML and JavaScript brings it to life, the body of your web application is its HTML. HTML's syntax even reflects that idea, as it includes "head", "body", and "footer" tags.
|
||||
|
||||
In this lesson, we're going to use HTML to layout the 'skeleton' of our virtual terrarium's interface. It will have a title and three columns: a right and left column where the draggable plants live, and a center area that will be the actual glass-looking terrarium. By the end of this lesson, you will be able to see the plants in the columns, but the interface will look a little strange; don't worry, in the next section you will add CSS styles to the interface to make it look better.
|
||||
|
||||
### Task:
|
||||
|
||||
On your computer, create a folder called 'terrarium' and inside it, a file called 'index.html'. You can do this in Visual Studio Code after you create your terrarium folder by opening a new VS Code window, clicking 'open folder', and navigating to your new folder. Click the small 'file' button in the Explorer pane and create the new file:
|
||||
|
||||

|
||||
|
||||
> index.html files indicate to a browser that it is the default file in a folder; URLs such as `https://anysite.com/test` might be built using a folder structure including a folder called `test` with `index.html` inside it; `index.html` doesn't have to show in a URL.
|
||||
|
||||
---
|
||||
|
||||
## 1. The DocType and html tags
|
||||
|
||||
The first line of an HTML file is its doctype. It's a little surprising that you need to have this line at the very top of the file, but it tells older browsers that the browser needs to render the page in a standard mode, following the current html specification.
|
||||
|
||||
> Tip: in VS Code, you can hover over a tag and get information about its use from the MDN Reference guides.
|
||||
|
||||
The second line should be the `<html>` tag's opening tag, followed right now by its closing tag. These tags are the root elements of your interface.
|
||||
|
||||
### Task:
|
||||
|
||||
Add these lines at the top of your `index.html` file:
|
||||
|
||||
```HTML
|
||||
<!DOCTYPE html>
|
||||
<html></html>
|
||||
```
|
||||
|
||||
✅ There are a few different modes that can be determined by setting the DocType with a query string: [Quirks Mode and Standards Mode](https://developer.mozilla.org/en-US/docs/Web/HTML/Quirks_Mode_and_Standards_Mode). These modes used to support really old browsers that aren't normally used nowadays (Netscape Navigator 4 and Internet Explorer 5). You can stick to the standard doctype declaration.
|
||||
|
||||
---
|
||||
|
||||
## 2. The document's 'head'
|
||||
|
||||
The 'head' area of the HTML document includes crucial information about your web page, also known as [metadata](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta). In our case, we tell the web server to which this page will be sent to be rendered four things:
|
||||
|
||||
- the page's title
|
||||
- page metadata including:
|
||||
- the 'character set', telling about what character encoding is used in the page
|
||||
- browser information, including `x-ua-compatible` which indicates that the IE=edge browser is supported
|
||||
- information about how the viewport should behave when it is loaded. Setting the viewport to have an initial scale of 1 controls the zoom level when the page is first loaded.
|
||||
|
||||
### Task:
|
||||
|
||||
Add a 'head' block to your document in between the opening and closing `<html>` tags.
|
||||
|
||||
```html
|
||||
<head>
|
||||
<title>Welcome to my Virtual Terrarium</title>
|
||||
<meta charset="utf-8" />
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
</head>
|
||||
```
|
||||
|
||||
✅ What would happen if you set a viewport meta tag like this: `<meta name="viewport" content="width=600">`? Read more about the [viewport](https://developer.mozilla.org/en-US/docs/Mozilla/Mobile/Viewport_meta_tag).
|
||||
|
||||
---
|
||||
|
||||
## 3. The document's `body`
|
||||
|
||||
### HTML Tags
|
||||
|
||||
In HTML, you add tags to your .html file to create elements of a web page. Each tag usually has an opening and closing tag, like this: `<p>hello</p>` to indicate a paragraph. Create you interface's `<body>` by adding a set of tags inside the `<html>` tag pair; your markup now looks like this:
|
||||
|
||||
### Task:
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Welcome to my Virtual Terrarium</title>
|
||||
<meta charset="utf-8" />
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
</head>
|
||||
<body></body>
|
||||
</html>
|
||||
```
|
||||
|
||||
Now, you can start building out your page. Normally, you use `<div>` tags to create the separate elements in a page. We'll create a series of `<div>` elements which will contain images.
|
||||
|
||||
### Images
|
||||
|
||||
One html tag that doesn't need a closing tag is the `<img>` tag, because it has a `src` element that contains all the information the page needs to render the item.
|
||||
|
||||
Create a folder in your app called `images` and in that, add all the images in the [source code folder](../images); (there are 14 images of plants).
|
||||
|
||||
### Task:
|
||||
|
||||
Add those plant images into two columns between the `<body></body>` tags:
|
||||
|
||||
```html
|
||||
<div id="page">
|
||||
<div id="left-container" class="container">
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant1" src="./images/plant1.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant2" src="./images/plant2.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant3" src="./images/plant3.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant4" src="./images/plant4.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant5" src="./images/plant5.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant6" src="./images/plant6.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant7" src="./images/plant7.png" />
|
||||
</div>
|
||||
</div>
|
||||
<div id="right-container" class="container">
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant8" src="./images/plant8.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant9" src="./images/plant9.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant10" src="./images/plant10.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant11" src="./images/plant11.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant12" src="./images/plant12.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant13" src="./images/plant13.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant14" src="./images/plant14.png" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
> Note: Spans vs. Divs. Divs are considered 'block' elements, and Spans are 'inline'. What would happen if you transformed these divs to spans?
|
||||
|
||||
With this markup, the plants now show up on the screen. It looks pretty bad, because they aren't yet styled using CSS, and we'll do that in the next lesson.
|
||||
|
||||
Each image has an alt tag that will appear even if you can't see or render an image. This is an important element to include for accessibility. Learn more about accessibility in future lessons; for now, remember that it's important to enable screen readers to step through your web app so that visually impaired users can use your web site.
|
||||
|
||||
✅ Did you notice that each image has the same alt tag? Is this good practice? Why or why not? Can you improve this code?
|
||||
|
||||
---
|
||||
|
||||
## 4. Semantic markup
|
||||
|
||||
In general, it's preferable to use 'semantics' when writing HTML. What does that mean? It means that you use HTML tags the way they were designed: to represent its data; so an H1 tag should always be present on a page
|
||||
|
||||
Add the following line right below your opening `<body>` tag:
|
||||
|
||||
```html
|
||||
<h1>My Terrarium</h1>
|
||||
```
|
||||
|
||||
Using semantic markup such as having headers be `<h1>` and unordered lists be rendered as `<ul>` helps screen readers navigate through a page. In general, buttons should be written as `<button>` and lists should be `<li>`. While it's _possible_ to use specially styled `<span>` elements with click handlers to mock buttons, it's better for differently-abled users to use technologies to determine where on a page a button resides, and to interact with it, if the element appears as a button. For this reason, try to use semantic markup as much as possible.
|
||||
|
||||
✅ Take a look at a screen reader and [how it interacts with a web page](https://www.youtube.com/watch?v=OUDV1gqs9GA). Can you see why having non semantic markup might confuse the user?
|
||||
|
||||
## 5. The terrarium
|
||||
|
||||
The last part of this interface involves creating markup that will be styled to create a terrarium.
|
||||
|
||||
### Task:
|
||||
|
||||
Add this markup above the last `</div>` tag:
|
||||
|
||||
```html
|
||||
<div id="terrarium">
|
||||
<div class="jar-top"></div>
|
||||
<div class="jar-walls">
|
||||
<div class="jar-glossy-long"></div>
|
||||
<div class="jar-glossy-short"></div>
|
||||
</div>
|
||||
<div class="dirt"></div>
|
||||
<div class="jar-bottom"></div>
|
||||
</div>
|
||||
```
|
||||
|
||||
✅ Even though you added this markup to the screen, you see absolutely nothing render. Why?
|
||||
|
||||
---
|
||||
|
||||
## 🚀Challenge
|
||||
|
||||
There are some wild 'older' tags in HTML that are still fun to play with, though you shouldn't use deprecated tags such as [these tags](https://developer.mozilla.org/en-US/docs/Web/HTML/Element) in your markup. Still, can you use the old `<marquee>` tag to make the h1 title scroll horizontally? (if you do, don't forget to remove it afterwards)
|
||||
|
||||
## [Post-lecture quiz](.github/post-lecture-quiz.md)
|
||||
|
||||
## Review & Self Study
|
||||
|
||||
HTML is the 'tried and true' building block system that has helped build the web into what it is today. Learn a little about its history by studying some old and new tags. Can you figure out why some tags were deprecated and some added? What tags might be introduced in the future?
|
||||
|
||||
Learn more about building sites for the web and mobile devices at [Microsoft Learn](https://docs.microsoft.com/learn/modules/build-simple-website/?WT.mc_id=webdev101-github-jelooper).
|
||||
|
||||
|
||||
## Assignment
|
||||
|
||||
[Practice your HTML: Build a blog mockup](assignment.md)
|
11
3-terrarium/1-intro-to-html/assignment.md
Normal file
@@ -0,0 +1,11 @@
|
||||
# Practice your HTML: Build a blog mockup
|
||||
|
||||
## Instructions
|
||||
|
||||
Imagine you are designing, or redesigning, your personal web site. Create a graphical markup of your site, and then write down the HTML markup you would use to build out the various elements of the site. You can do this on paper, and scan it, or use software of your choice, just make sure to hand-code the HTML markup.
|
||||
|
||||
## Rubric
|
||||
|
||||
| Criteria | Exemplary | Adequate | Needs Improvement |
|
||||
| -------- | ----------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
|
||||
| | A blog layout is represented visually with at least 10 elements of markup displayed | A blog layout is represented visually with around 5 elements of markup displayed | A blog layout is represented visually with at most 3 elements of markup displayed |
|
BIN
3-terrarium/1-intro-to-html/images/vs-code-index.png
Normal file
After Width: | Height: | Size: 34 KiB |
BIN
3-terrarium/1-intro-to-html/images/webdev101-html.png
Normal file
After Width: | Height: | Size: 1.6 MiB |
214
3-terrarium/1-intro-to-html/translations/README.es.md
Normal file
@@ -0,0 +1,214 @@
|
||||
# Terrarium Project Parte 1: Introducción a HTML
|
||||
|
||||

|
||||
> Sketchnote por [Tomomi Imura](https://twitter.com/girlie_mac)
|
||||
|
||||
## [Pre-lecture prueba](.github/pre-lecture-quiz.md)
|
||||
|
||||
### Introducción:
|
||||
|
||||
HTML, o HyperText Markup Language, es el "esqueleto" de la web. Si CSS 'viste' su HTML y JavaScript le da vida, el cuerpo de su aplicación web es su HTML. La sintaxis de HTML incluso refleja esa idea, ya que incluye etiquetas "head", "body" y "footer".
|
||||
|
||||
En esta lección, usaremos HTML para diseñar el 'esqueleto' de la interfaz de nuestro terrario virtual. Tendrá un título y tres columnas: una columna derecha e izquierda donde viven las plantas que se pueden arrastrar, y un área central que será el terrario de vidrio real. Al final de esta lección, podrá ver las plantas en las columnas, pero la interfaz se verá un poco extraña; no se preocupe, en la siguiente sección agregará estilos CSS a la interfaz para que se vea mejor.
|
||||
|
||||
### Tarea:
|
||||
|
||||
En su computadora, cree una carpeta llamada 'terrario' y dentro de ella, un archivo llamado 'index.html'. Puede hacer esto en Visual Studio Code después de crear su carpeta de terrario abriendo una nueva ventana de VS Code, haciendo clic en 'abrir carpeta' y navegando a su nueva carpeta. Haga clic en el botón pequeño 'archivo' en el panel del Explorador y cree el nuevo archivo:
|
||||
|
||||
! [explorador en VS Code] (images / vs-code-index.png)
|
||||
|
||||
> Los archivos index.html indican a un navegador que es el archivo predeterminado en una carpeta; Las URL como `https://anysite.com/test` se pueden construir usando una estructura de carpetas que incluya una carpeta llamada `test` con `index.html` dentro; `Index.html` no tiene que aparecer en una URL.
|
||||
|
||||
---
|
||||
|
||||
## 1. Las etiquetas DocType y html
|
||||
|
||||
La primera línea de un archivo HTML es su doctype. Es un poco sorprendente que necesite tener esta línea en la parte superior del archivo, pero le dice a los navegadores más antiguos que el navegador necesita representar la página en un modo estándar, siguiendo la especificación html actual.
|
||||
|
||||
> Consejo: en VS Code, puede colocar el cursor sobre una etiqueta y obtener información sobre su uso en las guías de referencia de MDN.
|
||||
|
||||
La segunda línea debe ser la etiqueta de apertura de la etiqueta `<html>`, seguida ahora por su etiqueta de cierre. Estas etiquetas son los elementos raíz de su interfaz.
|
||||
|
||||
### Tarea:
|
||||
|
||||
Agrega estas líneas en la parte superior de tu archivo `index.html`:
|
||||
|
||||
|
||||
```HTML
|
||||
<!DOCTYPE html>
|
||||
<html></html>
|
||||
```
|
||||
|
||||
✅ Hay algunos modos diferentes que se pueden determinar configurando DocType con una cadena de consulta: [Modo Quirks y Modo estándar](https://developer.mozilla.org/en-US/docs/Web/HTML/Quirks_Mode_and_Standards_Mode). Estos modos solían admitir navegadores realmente antiguos que no se utilizan normalmente en la actualidad (Netscape Navigator 4 e Internet Explorer 5). Puede ceñirse a la declaración de tipo de documento estándar.
|
||||
|
||||
---
|
||||
|
||||
## 2. El 'encabezado' del documento
|
||||
|
||||
El área 'encabezado' del documento HTML incluye información crucial sobre su página web, también conocida como [metadatos](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta). En nuestro caso, le decimos al servidor web al que se enviará esta página para que sea renderizada cuatro cosas:
|
||||
|
||||
- el título de la página
|
||||
- metadatos de la página que incluyen:
|
||||
- el 'conjunto de caracteres', que indica qué codificación de caracteres se utiliza en la página
|
||||
- información del navegador, incluido `x-ua-compatible`, que indica que el navegador IE = edge es compatible
|
||||
- información sobre cómo debería comportarse la ventana gráfica cuando se carga. Configurar la ventana gráfica para que tenga una escala inicial de 1 controla el nivel de zoom cuando la página se carga por primera vez.
|
||||
|
||||
### Tarea:
|
||||
|
||||
Agregue un bloque de 'encabezado' a su documento entre las etiquetas de apertura y cierre `<html>`.
|
||||
|
||||
```html
|
||||
<head>
|
||||
<title>Bienvenida a mi terrario virtual</title>
|
||||
<meta charset="utf-8" />
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
</head>
|
||||
```
|
||||
|
||||
✅ ¿Qué pasaría si configuras una metaetiqueta de ventana gráfica como esta: `<meta name =" viewport "content =" width = 600 ">`? Obtenga más información sobre [viewport](https://developer.mozilla.org/en-US/docs/Mozilla/Mobile/Viewport_meta_tag).
|
||||
|
||||
---
|
||||
|
||||
## 3. El `cuerpo` del documento
|
||||
|
||||
### Etiquetas HTML
|
||||
|
||||
En HTML, agrega etiquetas a su archivo .html para crear elementos de una página web. Cada etiqueta generalmente tiene una etiqueta de apertura y cierre, como esta: `<p>hola</p>` para indicar un párrafo. Cree su interfaz `<body>` agregando un conjunto de etiquetas dentro del par de etiquetas `<html>`; su marcado ahora se ve así:
|
||||
|
||||
### Tarea:
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Bienvenida a mi terrario virtual</title>
|
||||
<meta charset="utf-8" />
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
</head>
|
||||
<body></body>
|
||||
</html>
|
||||
```
|
||||
|
||||
Ahora, puede comenzar a construir su página. Normalmente, usa etiquetas `<div>` para crear los elementos separados en una página. Crearemos una serie de elementos `<div>` que contendrán imágenes.
|
||||
|
||||
### Imágenes
|
||||
|
||||
Una etiqueta html que no necesita una etiqueta de cierre es la etiqueta `<img>`, porque tiene un elemento `src` que contiene toda la información que la página necesita para representar el elemento.
|
||||
|
||||
Cree una carpeta en su aplicación llamada `images` y en ella, agregue todas las imágenes en la [carpeta del código fuente] (../ images); (hay 14 imágenes de plantas).
|
||||
|
||||
### Tarea:
|
||||
|
||||
Agregue esas imágenes de plantas en dos columnas entre las etiquetas `<body> </body>`:
|
||||
|
||||
|
||||
```html
|
||||
<div id="page">
|
||||
<div id="left-container" class="container">
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant1" src="./images/plant1.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant2" src="./images/plant2.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant3" src="./images/plant3.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant4" src="./images/plant4.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant5" src="./images/plant5.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant6" src="./images/plant6.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant7" src="./images/plant7.png" />
|
||||
</div>
|
||||
</div>
|
||||
<div id="right-container" class="container">
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant8" src="./images/plant8.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant9" src="./images/plant9.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant10" src="./images/plant10.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant11" src="./images/plant11.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant12" src="./images/plant12.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant13" src="./images/plant13.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant14" src="./images/plant14.png" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
> Nota: Spans vs. Divs. Los Divs se consideran elementos de 'bloque' y los Spans están 'en línea'. ¿Qué pasaría si transformaras estos divs en tramos?
|
||||
|
||||
Con este marcado, las plantas ahora aparecen en la pantalla. Se ve bastante mal, porque aún no están diseñados con CSS, y lo haremos en la próxima lección.
|
||||
|
||||
Cada imagen tiene una etiqueta alt que aparecerá incluso si no puede ver o representar una imagen. Este es un elemento importante a incluir para la accesibilidad. Obtenga más información sobre accesibilidad en lecciones futuras; Por ahora, recuerde que es importante permitir que los lectores de pantalla recorran su aplicación web para que los usuarios con discapacidad visual puedan utilizar su sitio web.
|
||||
|
||||
✅ ¿Notaste que cada imagen tiene la misma etiqueta alt? ¿Es esta una buena práctica? ¿Por qué o por qué no? ¿Puedes mejorar este código?
|
||||
|
||||
---
|
||||
|
||||
## 4. Marcado semántico
|
||||
|
||||
En general, es preferible usar 'semántica' al escribir HTML. Qué significa eso? Significa que utiliza etiquetas HTML de la forma en que fueron diseñadas: para representar sus datos; por lo que una etiqueta H1 siempre debe estar presente en una página
|
||||
|
||||
Agrega la siguiente línea justo debajo de tu etiqueta de apertura `<body>`:
|
||||
|
||||
```html
|
||||
<h1>Mi terrario</h1>
|
||||
```
|
||||
|
||||
El uso de marcado semántico, como que los encabezados sean `<h1>` y las listas desordenadas se representen como `<ul>`, ayuda a los lectores de pantalla a navegar por una página. En general, los botones deben escribirse como `<button>` y las listas deben ser `<li>`. Si bien es _posible_ usar elementos `<span>` de estilo especial con controladores de clic para simular botones, es mejor que los usuarios con capacidades diferentes usen tecnologías para determinar en qué parte de una página reside un botón e interactuar con él, si el elemento aparece como un botón. Por esta razón, intente utilizar el marcado semántico tanto como sea posible.
|
||||
|
||||
✅ Eche un vistazo a un lector de pantalla y [cómo interactúa con una página web](https://www.youtube.com/watch?v=OUDV1gqs9GA). ¿Puedes ver por qué tener un marcado no semántico podría confundir al usuario?
|
||||
|
||||
## 5. El terrario
|
||||
|
||||
La última parte de esta interfaz implica la creación de marcas que se diseñarán para crear un terrario.
|
||||
|
||||
### Tarea:
|
||||
|
||||
Agregue este marcado encima de la última etiqueta `</div>`:
|
||||
|
||||
```html
|
||||
<div id="terrarium">
|
||||
<div class="jar-top"></div>
|
||||
<div class="jar-walls">
|
||||
<div class="jar-glossy-long"></div>
|
||||
<div class="jar-glossy-short"></div>
|
||||
</div>
|
||||
<div class="dirt"></div>
|
||||
<div class="jar-bottom"></div>
|
||||
</div>
|
||||
```
|
||||
|
||||
✅ Aunque agregó este marcado a la pantalla, no ve absolutamente nada renderizado. ¿Por qué?
|
||||
|
||||
---
|
||||
|
||||
🚀 Desafío: hay algunas etiquetas "antiguas" salvajes en HTML con las que todavía es divertido jugar, aunque no debes usar etiquetas obsoletas como [estas etiquetas](https://developer.mozilla.org/en-US/docs/Web/HTML/Element) en su marcado. Aún así, ¿puede usar la antigua etiqueta `<marquee>` para hacer que el título h1 se desplace horizontalmente? (si lo hace, no olvide quitarlo después)
|
||||
|
||||
## [Post-lecture prueba](.github/post-lecture-quiz.md)
|
||||
|
||||
## Revisión y autoestudio
|
||||
|
||||
HTML es el sistema de bloques de construcción 'probado y verdadero' que ha ayudado a convertir la web en lo que es hoy. Aprenda un poco sobre su historia estudiando algunas etiquetas antiguas y nuevas. ¿Puedes averiguar por qué algunas etiquetas quedaron obsoletas y otras se agregaron? ¿Qué etiquetas podrían introducirse en el futuro?
|
||||
|
||||
** Tarea: [Practica tu HTML: crea una maqueta de blog](assignment.md)
|
11
3-terrarium/1-intro-to-html/translations/assignment.es.md
Normal file
@@ -0,0 +1,11 @@
|
||||
# Practica tu HTML: crea una maqueta de blog
|
||||
|
||||
## Instrucciones
|
||||
|
||||
Imagínese que está diseñando o rediseñando su sitio web personal. Cree un marcado gráfico de su sitio y luego escriba el marcado HTML que usaría para construir los diversos elementos del sitio. Puede hacer esto en papel y escanearlo, o usar el software de su elección, solo asegúrese de codificar manualmente el marcado HTML.
|
||||
|
||||
## Rúbrica
|
||||
|
||||
| Criterios | Ejemplar | Adecuado | Necesita mejorar |
|
||||
| -------- | -------------------------------------------------- --------------------------------- | -------------------------------------------------- ------------------------------ | -------------------------------------------------- ------------------------------- |
|
||||
| | El diseño de un blog se representa visualmente con al menos 10 elementos de marcado mostrados | Un diseño de blog se representa visualmente con alrededor de 5 elementos de marcado mostrados | El diseño de un blog se representa visualmente con un máximo de 3 elementos de marcado mostrados |
|
21
3-terrarium/2-intro-to-css/.github/post-lecture-quiz.md
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
*Complete this quiz after the lesson by checking one answer per question.*
|
||||
|
||||
You will need to reference the following learn module to complete the quiz:
|
||||
|
||||
[Work with CSS](https://docs.microsoft.com/en-us/learn/modules/build-simple-website/4-css-basics)
|
||||
|
||||
1. [You can write CSS directly in the head section of your HTML file]
|
||||
|
||||
- [ ] [true]
|
||||
- [ ] [false]
|
||||
|
||||
1. [It's always necessary to include CSS in your app]
|
||||
|
||||
- [ ] [true]
|
||||
- [ ] [false]
|
||||
- [ ] [false, but if you want it to look good you need CSS]
|
||||
|
||||
1. [Which browser tool can be used to inspect CSS?]
|
||||
- [ ] [Elements]
|
||||
- [ ] [Styles]
|
||||
- [ ] [Network]
|
18
3-terrarium/2-intro-to-css/.github/pre-lecture-quiz.md
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
*A warm-up quiz about CSS*
|
||||
|
||||
Complete this quiz in class
|
||||
|
||||
1. HTML elements must have either a class or an id in order to be styled
|
||||
|
||||
- [ ] [true]
|
||||
- [ ] [false]
|
||||
|
||||
2. CSS stands for 'Complete Style Sheets'
|
||||
|
||||
- [ ] [true]
|
||||
- [ ] [false]
|
||||
|
||||
3. CSS can be used to create animations
|
||||
|
||||
- [ ] [true]
|
||||
- [ ] [false]
|
259
3-terrarium/2-intro-to-css/README.md
Normal file
@@ -0,0 +1,259 @@
|
||||
# Terrarium Project Part 2: Introduction to CSS
|
||||
|
||||

|
||||
> Sketchnote by [Tomomi Imura](https://twitter.com/girlie_mac)
|
||||
|
||||
## [Pre-lecture quiz](.github/pre-lecture-quiz.md)
|
||||
|
||||
### Introduction:
|
||||
|
||||
CSS, or Cascading Style Sheets, solve an important problem of web development: how to make your web site look nice. Styling your apps makes them more usable and nicer-looking; you can also use CSS to create Responsive Web Design (RWD) - allowing your apps to look good no matter what screen size they are displayed on. CSS is not only about making your app look nice; its spec includes animations and transforms that can enable sophisticated interactions for your apps. The CSS Working Group helps maintain current CSS specifications; you can follow their work at [World Wide Web Consortium's site](https://www.w3.org/Style/CSS/members).
|
||||
|
||||
> Note, CSS is a language that evolves, like everything on the web, and not all browsers support newer parts of the specification. Always check your implementations by consulting [CanIUse.com](caniuse.com).
|
||||
|
||||
In this lesson, we're going to add styles to our online terrarium and learn more about several CSS concepts: the cascade, inheritance, and the use of selectors, positioning, and using CSS to build layouts. In the process we will layout the terrarium and create the actual terrarium itself.
|
||||
|
||||
### Prequisite:
|
||||
|
||||
You should have the HTML for your terrarium built and ready to be styled.
|
||||
|
||||
### Task:
|
||||
|
||||
In your terrarium folder, create a new file called `style.css`. Import that file in the `<head>` section:
|
||||
|
||||
```
|
||||
<link rel="stylesheet" href="./style.css" />
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 1. The Cascade
|
||||
|
||||
Cascading Style Sheets incorporate the idea that the styles 'cascade' such that the application of a style is guided by its priority. Styles set by a web site author take priority over those set by a browser. Styles set 'inline' take priority over those set in an external style sheet.
|
||||
|
||||
### Task:
|
||||
|
||||
Add the inline style "color: red" to your `<h1>` tag:
|
||||
|
||||
```HTML
|
||||
<h1 style="color: red">My Terrarium</h1>
|
||||
```
|
||||
|
||||
Then, add the following code to your `style.css` file:
|
||||
|
||||
```CSS
|
||||
h1 {
|
||||
color: blue;
|
||||
}
|
||||
```
|
||||
|
||||
✅ Which color displays in your web app? Why? Can you find a way to override styles? When would you want to do this, or why not?
|
||||
|
||||
---
|
||||
|
||||
## 2. Inheritance
|
||||
|
||||
Styles are inherited from an ancestor style to a descendent, such that nested elements inherit the styles of their parents.
|
||||
|
||||
### Task:
|
||||
|
||||
Set the body's font to a given font, and check to see a nested element's font:
|
||||
|
||||
```
|
||||
body {
|
||||
font-family: helvetica, arial, sans-serif;
|
||||
}
|
||||
```
|
||||
|
||||
Open your browser's console to the 'Elements' tab and observe the H1's font. It inherits its font from the body, as stated within the browser:
|
||||
|
||||

|
||||
|
||||
✅ Can you make a nested style inherit a different property?
|
||||
|
||||
---
|
||||
|
||||
## 3. CSS Selectors
|
||||
|
||||
### Tags
|
||||
|
||||
So far, your `style.css` file has only a few tags styled, and the app looks pretty strange:
|
||||
|
||||
```
|
||||
body {
|
||||
font-family: helvetica, arial, sans-serif;
|
||||
}
|
||||
|
||||
h1 {
|
||||
color: #3a241d;
|
||||
text-align: center;
|
||||
}
|
||||
```
|
||||
|
||||
This way of styling a tag gives you control over unique elements, but you need to control the styles of many plants in your terrarium. To do that, you need to leverage CSS selectors.
|
||||
|
||||
### Ids
|
||||
|
||||
Add some style to layout the left and right containers. Since there is only one left container and only one right container, they are given ids in the markup. To style them, use `#`:
|
||||
|
||||
```
|
||||
#left-container {
|
||||
background-color: #eee;
|
||||
width: 15%;
|
||||
left: 0px;
|
||||
top: 0px;
|
||||
position: absolute;
|
||||
height: 100%;
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
#right-container {
|
||||
background-color: #eee;
|
||||
width: 15%;
|
||||
right: 0px;
|
||||
top: 0px;
|
||||
position: absolute;
|
||||
height: 100%;
|
||||
padding: 10px;
|
||||
}
|
||||
```
|
||||
|
||||
Here, you have placed these containers with absolute positioning to the far left and right of the screen, and used percentages for their width so that they can scale for small mobile screens.
|
||||
|
||||
✅ This code is quite repeated, thus not "DRY" (Don't Repeat Yourself); can you find a better way to style these ids, perhaps with an id and a class? You would need to change the markup and refactor the CSS:
|
||||
|
||||
```html
|
||||
<div id="left-container" class="container"></div>
|
||||
```
|
||||
|
||||
### Classes
|
||||
|
||||
In the example above, you styled two unique elements on the screen. If you want styles to apply to many elements on the screen, you can use CSS classes. Do this to layout the plants in the left and right containers.
|
||||
|
||||
Notice that each plant in the HTML markup has a combination of ids and classes. The ids here are used by the JavaScript that you will add later to manipulate the terrarium plant placement. The classes, however, give all the plants a given style.
|
||||
|
||||
```html
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant1" src="./images/plant1.png" />
|
||||
</div>
|
||||
```
|
||||
|
||||
Add the following to your `style.css` file:
|
||||
|
||||
```css
|
||||
.plant-holder {
|
||||
position: relative;
|
||||
height: 13%;
|
||||
left: -10px;
|
||||
}
|
||||
|
||||
.plant {
|
||||
position: absolute;
|
||||
max-width: 150%;
|
||||
max-height: 150%;
|
||||
z-index: 2;
|
||||
}
|
||||
```
|
||||
|
||||
Notable in this snippet is the mixture of relative and absolute positioning, which we'll cover in the next section. Take a look at the way heights are handled by percentages:
|
||||
|
||||
You set the height of the plant holder to 13%, a good number to ensure that all the plants are displayed in each vertical container without need for scrolling.
|
||||
|
||||
You set the plant holder to move to the left to allow the plants to be more centered within their container. The images have a large amount of transparent background so as to make them more draggable, so need to be pushed to the left to fit better on the screen.
|
||||
|
||||
Then, the plant itself is given a max-width of 150%. This allows it to scale down as the browser scales down. Try resizing your browser; the plants stay in their containers but scale down to fit.
|
||||
|
||||
Also notable is the use of z-index, which controls the relative altitude of an element (so that the plants sit on top of the container and appear to sit inside the terrarium).
|
||||
|
||||
✅ Why do you need both a plant holder and a plant CSS selector?
|
||||
|
||||
## 4. CSS Positioning
|
||||
|
||||
Mixing position properties (there are static, relative, fixed, absolute, and sticky positions) can be a little tricky, but when done properly it gives you good control over the elements on your pages.
|
||||
|
||||
Absolute positioned elements are positioned relative to their nearest positioned ancestors, and if there are none, it is positioned according to the document body.
|
||||
|
||||
Relative positioned elements are positioned based on the CSS's directions to adjust its placement away from its initial position.
|
||||
|
||||
In our sample, the `plant-holder` is a relative-positioned element that is positioned within an absolute-positioned container. The resultant behavior is that the side bar containers are pinned left and right, and the plant-holder is nested, adjusting itself within the side bars, giving space for the plants to be placed in a vertical row.
|
||||
|
||||
> The `plant` itself also has absolute positioning, necessary to making it draggable, as you will discover in the next lesson.
|
||||
|
||||
✅ Experiment with switching the types of positioning of the side containers and the plant-holder. What happens?
|
||||
|
||||
## 5. CSS Layouts
|
||||
|
||||
Now you will use what you learned to build the terrarium itself, all using CSS!
|
||||
|
||||
First, style the `.terrarium` div children as a rounded rectangle using CSS:
|
||||
|
||||
```css
|
||||
.jar-walls {
|
||||
height: 80%;
|
||||
width: 60%;
|
||||
background: #d1e1df;
|
||||
border-radius: 10%;
|
||||
position: absolute;
|
||||
bottom: 0.5%;
|
||||
left: 20%;
|
||||
opacity: 0.5;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.jar-top {
|
||||
width: 50%;
|
||||
height: 5%;
|
||||
background: #d1e1df;
|
||||
position: absolute;
|
||||
bottom: 80.5%;
|
||||
left: 25%;
|
||||
opacity: 0.7;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.jar-bottom {
|
||||
width: 50%;
|
||||
height: 1%;
|
||||
background: #d1e1df;
|
||||
position: absolute;
|
||||
bottom: 0%;
|
||||
left: 25%;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.dirt {
|
||||
width: 58%;
|
||||
height: 5%;
|
||||
background: #3a241d;
|
||||
position: absolute;
|
||||
border-radius: 0 0 4rem 4rem;
|
||||
bottom: 1%;
|
||||
left: 21%;
|
||||
opacity: 0.7;
|
||||
z-index: -1;
|
||||
}
|
||||
```
|
||||
|
||||
Note the use of percentages here, even for the `border-radius`. If you scale your browser down, you can see how the jar corners scale as well. Also notice the widths and height percentages for the jar elements and how each element is absolutely positioned in the center, pinned to the bottom of the viewport.
|
||||
|
||||
✅ Try changing the jar colors and opacity vs. those of the dirt. What happens? Why?
|
||||
|
||||
---
|
||||
|
||||
## 🚀Challenge
|
||||
|
||||
Add a 'bubble' shine to the left bottom area of the jar to make it look more glasslike. You will be styling the `.jar-glossy-long` and `.jar-glossy-short` to look like a reflected shine. Here's how it would look:
|
||||
|
||||

|
||||
|
||||
To complete the post-lecture quiz, go through this Learn module: [Style your HTML app with CSS](https://docs.microsoft.com/en-us/learn/modules/build-simple-website/4-css-basics)
|
||||
|
||||
## [Post-lecture quiz](.github/post-lecture-quiz.md)
|
||||
|
||||
## Review & Self Study
|
||||
|
||||
CSS seems deceptively straightforward, but there are many challenges when trying to style an app perfectly for all browsers and all screen sizes. CSS-Grid and Flexbox are tools that have been developed to make the job a little more structured and more reliable. Learn about these tools by playing [Flexbox Froggy](https://flexboxfroggy.com/) and [Grid Garden](https://codepip.com/games/grid-garden/).
|
||||
|
||||
## Assignment
|
||||
|
||||
[CSS Refactoring](assignment.md)
|
11
3-terrarium/2-intro-to-css/assignment.md
Normal file
@@ -0,0 +1,11 @@
|
||||
# CSS Refactoring
|
||||
|
||||
## Instructions
|
||||
|
||||
Restyle the terrarium using either Flexbox or CSS Grid, and take screenshots to show that you have tested it on several browsers. You might need to change the markup so create a new version of the app with the art in place for your refactor. Don't worry about making the elements draggable; only refactor the HTML and CSS for now.
|
||||
|
||||
## Rubric
|
||||
|
||||
| Criteria | Exemplary | Adequate | Needs Improvement |
|
||||
| -------- | ----------------------------------------------------------------- | ----------------------------- | ------------------------------------ |
|
||||
| | Present a completely restyled terrarium using Flexbox or CSS Grid | Restyle a few of the elements | Fail to restyle the terrarium at all |
|
BIN
3-terrarium/2-intro-to-css/images/1.png
Normal file
After Width: | Height: | Size: 9.3 KiB |
BIN
3-terrarium/2-intro-to-css/images/terrarium-final.png
Normal file
After Width: | Height: | Size: 919 KiB |
BIN
3-terrarium/2-intro-to-css/images/webdev101-css.png
Normal file
After Width: | Height: | Size: 1.4 MiB |
258
3-terrarium/2-intro-to-css/translations/README.es.md
Normal file
@@ -0,0 +1,258 @@
|
||||
# Terrarium Project Parte 2: Introducción a CSS
|
||||
|
||||

|
||||
> Sketchnote por [Tomomi Imura](https://twitter.com/girlie_mac)
|
||||
|
||||
## [Pre-lecture prueba](.github/pre-lecture-quiz.md)
|
||||
|
||||
### Introducción:
|
||||
|
||||
CSS, o Cascading Style Sheets, resuelve un problema importante del desarrollo web: cómo hacer que su sitio web se vea bien. Diseñar tus aplicaciones las hace más útiles y atractivas; También puede usar CSS para crear un diseño web receptivo (RWD), lo que permite que sus aplicaciones se vean bien sin importar en qué tamaño de pantalla se muestren. CSS no se trata solo de hacer que su aplicación se vea bien; su especificación incluye animaciones y transformaciones que pueden permitir interacciones sofisticadas para sus aplicaciones. El grupo de trabajo CSS ayuda a mantener las especificaciones CSS actuales; puede seguir su trabajo en el [sitio del World Wide Web Consortium](https://www.w3.org/Style/CSS/members).
|
||||
|
||||
> Tenga en cuenta que CSS es un lenguaje que evoluciona, como todo en la web, y no todos los navegadores admiten partes más nuevas de la especificación. Siempre verifique sus implementaciones consultando [CanIUse.com](caniuse.com).
|
||||
|
||||
En esta lección, agregaremos estilos a nuestro terrario en línea y aprenderemos más sobre varios conceptos de CSS: la cascada, la herencia y el uso de selectores, posicionamiento y uso de CSS para crear diseños. En el proceso, diseñaremos el terrario y crearemos el terrario en sí.
|
||||
|
||||
### Requisito previo:
|
||||
|
||||
Debería tener el HTML para su terrario construido y listo para darle estilo.
|
||||
|
||||
### Tarea:
|
||||
|
||||
En su carpeta de terrario, cree un nuevo archivo llamado `style.css`. Importe ese archivo en la sección `<head>`:
|
||||
|
||||
```
|
||||
<link rel="stylesheet" href="./style.css" />
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 1. La cascada
|
||||
|
||||
Las hojas de estilo en cascada incorporan la idea de que los estilos 'se mueven en cascada' de manera que la aplicación de un estilo está guiada por su prioridad. Los estilos establecidos por el autor de un sitio web tienen prioridad sobre los establecidos por un navegador. Los estilos configurados 'en línea' tienen prioridad sobre los configurados en una hoja de estilo externa.
|
||||
|
||||
### Tarea:
|
||||
|
||||
Agrega el estilo en línea "color: red" a tu etiqueta `<h1>`:
|
||||
|
||||
```HTML
|
||||
<h1 style="color: red">My Terrarium</h1>
|
||||
```
|
||||
|
||||
Luego, agregue el siguiente código a su archivo `style.css`:
|
||||
|
||||
```CSS
|
||||
h1 {
|
||||
color: blue;
|
||||
}
|
||||
```
|
||||
|
||||
✅ ¿Qué color se muestra en su aplicación web? ¿Por qué? ¿Puedes encontrar una forma de anular estilos? ¿Cuándo querría hacer esto o por qué no?
|
||||
|
||||
---
|
||||
|
||||
## 2. Herencia
|
||||
|
||||
Los estilos se heredan de un estilo antepasado a un estilo descendiente, de modo que los elementos anidados heredan los estilos de sus padres.
|
||||
|
||||
### Tarea:
|
||||
|
||||
Establezca la fuente del cuerpo en una fuente determinada y verifique para ver la fuente de un elemento anidado:
|
||||
|
||||
```
|
||||
body {
|
||||
font-family: helvetica, arial, sans-serif;
|
||||
}
|
||||
```
|
||||
|
||||
Abra la consola de su navegador en la pestaña 'Elementos' y observe la fuente H1. Hereda su fuente del cuerpo, como se indica en el navegador:
|
||||
|
||||

|
||||
|
||||
✅ ¿Puede hacer que un estilo anidado herede una propiedad diferente?
|
||||
|
||||
---
|
||||
|
||||
## 3. Selectores CSS
|
||||
|
||||
### Etiquetas
|
||||
|
||||
Hasta ahora, su archivo `style.css` tiene solo algunas etiquetas con estilo, y la aplicación se ve bastante extraña:
|
||||
|
||||
```
|
||||
body {
|
||||
font-family: helvetica, arial, sans-serif;
|
||||
}
|
||||
|
||||
h1 {
|
||||
color: #3a241d;
|
||||
text-align: center;
|
||||
}
|
||||
```
|
||||
|
||||
Esta forma de diseñar una etiqueta te da control sobre elementos únicos, pero necesitas controlar los estilos de muchas plantas en tu terrario. Para hacer eso, necesita aprovechar los selectores de CSS.
|
||||
|
||||
### ID
|
||||
|
||||
Agregue un poco de estilo para diseñar los contenedores izquierdo y derecho. Dado que solo hay un contenedor izquierdo y solo un contenedor derecho, se les dan identificadores en el marcado. Para diseñarlos, use `#`:
|
||||
|
||||
```
|
||||
#left-container {
|
||||
background-color: #eee;
|
||||
width: 15%;
|
||||
left: 0px;
|
||||
top: 0px;
|
||||
position: absolute;
|
||||
height: 100%;
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
#right-container {
|
||||
background-color: #eee;
|
||||
width: 15%;
|
||||
right: 0px;
|
||||
top: 0px;
|
||||
position: absolute;
|
||||
height: 100%;
|
||||
padding: 10px;
|
||||
}
|
||||
```
|
||||
|
||||
HAquí, ha colocado estos contenedores con posicionamiento absoluto en el extremo izquierdo y derecho de la pantalla, y ha utilizado porcentajes para su ancho para que puedan escalar para pantallas móviles pequeñas.
|
||||
|
||||
✅ Este código se repite bastante, por lo tanto, no "DRY" (Don't Repeat yourself: No se repita); ¿Puede encontrar una mejor manera de diseñar estos identificadores, tal vez con un id y una clase? Necesitaría cambiar el marcado y refactorizar el CSS:
|
||||
|
||||
```html
|
||||
<div id="left-container" class="container"></div>
|
||||
```
|
||||
|
||||
### Clases
|
||||
|
||||
En el ejemplo anterior, diseñó dos elementos únicos en la pantalla. Si desea que los estilos se apliquen a muchos elementos en la pantalla, puede usar clases CSS. Haga esto para colocar las plantas en los contenedores izquierdo y derecho.
|
||||
|
||||
Observe que cada planta en el marcado HTML tiene una combinación de identificadores y clases. Los identificadores aquí son utilizados por JavaScript que agregará más adelante para manipular la ubicación de la planta del terrario. Las clases, sin embargo, dan a todas las plantas un estilo determinado.
|
||||
|
||||
```html
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant1" src="./images/plant1.png" />
|
||||
</div>
|
||||
```
|
||||
|
||||
Agrega lo siguiente a tu archivo `style.css`:
|
||||
|
||||
```css
|
||||
.plant-holder {
|
||||
position: relative;
|
||||
height: 13%;
|
||||
left: -10px;
|
||||
}
|
||||
|
||||
.plant {
|
||||
position: absolute;
|
||||
max-width: 150%;
|
||||
max-height: 150%;
|
||||
z-index: 2;
|
||||
}
|
||||
```
|
||||
|
||||
En este fragmento se destaca la mezcla de posicionamiento relativo y absoluto, que cubriremos en la siguiente sección. Eche un vistazo a la forma en que se manejan las alturas por porcentajes:
|
||||
|
||||
Establece la altura del soporte de la planta en 13%, un buen número para garantizar que todas las plantas se muestren en cada contenedor vertical sin necesidad de desplazarse.
|
||||
|
||||
Configura el soporte de la planta para que se mueva hacia la izquierda para permitir que las plantas estén más centradas dentro de su contenedor. Las imágenes tienen una gran cantidad de fondo transparente para que se puedan arrastrar más, por lo que es necesario empujarlas hacia la izquierda para que quepan mejor en la pantalla.
|
||||
|
||||
Luego, a la planta en sí se le asigna un ancho máximo del 150%. Esto permite que se reduzca a medida que el navegador se reduce. Intente cambiar el tamaño de su navegador; las plantas permanecen en sus contenedores pero se reducen para adaptarse.
|
||||
|
||||
También es notable el uso del índice z, que controla la altitud relativa de un elemento (de modo que las plantas se sientan en la parte superior del contenedor y parezcan sentarse dentro del terrario).
|
||||
|
||||
✅ ¿Por qué necesita tanto un soporte para plantas como un selector CSS de plantas?
|
||||
|
||||
## 4. Posicionamiento CSS
|
||||
|
||||
Mezclar propiedades de posición (hay posiciones estáticas, relativas, fijas, absolutas y pegajosas) puede ser un poco complicado, pero cuando se hace correctamente, te da un buen control sobre los elementos de tus páginas.
|
||||
|
||||
Los elementos de posición absoluta se colocan en relación con sus antepasados colocados más cercanos y, si no hay ninguno, se colocan de acuerdo con el cuerpo del documento.
|
||||
|
||||
Los elementos de posición relativa se colocan según las direcciones del CSS para ajustar su ubicación lejos de su posición inicial.
|
||||
|
||||
En nuestra muestra, el "plant-holder" es un elemento de posición relativa que se coloca dentro de un contenedor de posición absoluta. El comportamiento resultante es que los contenedores de las barras laterales se sujetan a izquierda y derecha, y el portaplantas se encaja, ajustándose dentro de las barras laterales, dando espacio para que las plantas se coloquen en una fila vertical.
|
||||
|
||||
> La `planta` en sí también tiene un posicionamiento absoluto, necesario para que sea arrastrable, como descubrirás en la siguiente lección.
|
||||
|
||||
✅ Experimente cambiando los tipos de colocación de los contenedores laterales y el portaplantas. ¿Lo que pasa?
|
||||
|
||||
## 5. Diseños CSS
|
||||
|
||||
Ahora usará lo que aprendió para construir el terrario en sí, ¡todo usando CSS!
|
||||
|
||||
Primero, diseñe los elementos secundarios `.terrarium` div como un rectángulo redondeado usando CSS:
|
||||
|
||||
```css
|
||||
.jar-walls {
|
||||
height: 80%;
|
||||
width: 60%;
|
||||
background: #d1e1df;
|
||||
border-radius: 10%;
|
||||
position: absolute;
|
||||
bottom: 0.5%;
|
||||
left: 20%;
|
||||
opacity: 0.5;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.jar-top {
|
||||
width: 50%;
|
||||
height: 5%;
|
||||
background: #d1e1df;
|
||||
position: absolute;
|
||||
bottom: 80.5%;
|
||||
left: 25%;
|
||||
opacity: 0.7;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.jar-bottom {
|
||||
width: 50%;
|
||||
height: 1%;
|
||||
background: #d1e1df;
|
||||
position: absolute;
|
||||
bottom: 0%;
|
||||
left: 25%;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.dirt {
|
||||
width: 58%;
|
||||
height: 5%;
|
||||
background: #3a241d;
|
||||
position: absolute;
|
||||
border-radius: 0 0 4rem 4rem;
|
||||
bottom: 1%;
|
||||
left: 21%;
|
||||
opacity: 0.7;
|
||||
z-index: -1;
|
||||
}
|
||||
```
|
||||
|
||||
Tenga en cuenta el uso de porcentajes aquí, incluso para el `border-radius`. Si reduce la escala de su navegador, también puede ver cómo se escalan las esquinas del frasco. Observe también los porcentajes de ancho y alto de los elementos del tarro y cómo cada elemento está absolutamente posicionado en el centro, fijado a la parte inferior de la ventana gráfica.
|
||||
|
||||
✅ Intente cambiar los colores y la opacidad del frasco frente a los de la suciedad. ¿Lo que pasa? ¿Por qué?
|
||||
|
||||
---
|
||||
|
||||
🚀 Desafío: agregue un brillo de 'burbuja' al área inferior izquierda del frasco para que se vea más parecido al vidrio. Estarás diseñando el `.jar-glossy-long` y el` .jar-glossy-short` para que parezca un brillo reflejado. Así es como se vería:
|
||||
|
||||
! [terrario terminado](./images/terrarium-final.png)
|
||||
|
||||
## [Post-lecture prueba](.github/post-lecture-quiz.md)
|
||||
|
||||
## Revisión y autoestudio
|
||||
|
||||
CSS parece engañosamente sencillo, pero existen muchos desafíos cuando se trata de diseñar una aplicación perfectamente para todos los navegadores y todos los tamaños de pantalla. CSS-Grid y Flexbox son herramientas que se han desarrollado para hacer el trabajo un poco más estructurado y más confiable. Aprende sobre estas herramientas jugando a [Flexbox Froggy](https://flexboxfroggy.com/) y [Grid Garden](https://codepip.com/games/grid-garden/).
|
||||
|
||||
**Asignación**: [Refactorización CSS] (asignación.md)
|
||||
|
||||
Complete los siguientes módulos de aprendizaje para completar el [cuestionario posterior a la conferencia](. Github / post-lecture-quiz.md):
|
||||
|
||||
[Diseñe su aplicación HTML con CSS](https://docs.microsoft.com/en-us/learn/modules/build-simple-website/4-css-basics)
|
||||
|
11
3-terrarium/2-intro-to-css/translations/assignment.es.md
Normal file
@@ -0,0 +1,11 @@
|
||||
# Refactorización CSS
|
||||
|
||||
## Instrucciones
|
||||
|
||||
Cambie el estilo del terrario usando Flexbox o CSS Grid, y tome capturas de pantalla para mostrar que lo ha probado en varios navegadores. Es posible que deba cambiar el marcado, así que cree una nueva versión de la aplicación con el arte en su lugar para su refactorización. No se preocupe por hacer que los elementos se puedan arrastrar; solo refactorice el HTML y CSS por ahora.
|
||||
|
||||
## Rúbrica
|
||||
|
||||
| Criterios | Ejemplar | Adecuada | Necesita mejorar |
|
||||
| -------- | ----------------------------------------------------------------- | ----------------------------- | ------------------------------------ |
|
||||
| | Presenta un terrario completamente rediseñado usando Flexbox o CSS Grid | Modifique algunos de los elementos | No cambiar el estilo del terrario en absoluto |
|
18
3-terrarium/3-intro-to-DOM-and-closures/.github/post-lecture-quiz.md
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
*Complete this quiz after the lesson by checking one answer per question.*
|
||||
|
||||
1. [The DOM is a model to represent a document on the web]
|
||||
|
||||
- [ ] [true]
|
||||
- [ ] [false]
|
||||
|
||||
2. [Use JavaScript closures to perform the following:]
|
||||
|
||||
- [ ] [write functions within functions]
|
||||
- [ ] [enclose the DOM]
|
||||
- [ ] [close script blocks]
|
||||
|
||||
3. [Fill in the blank: Closures are useful when one or more functions need to access an outer function's ______]
|
||||
|
||||
- [ ] [arrays]
|
||||
- [ ] [scope]
|
||||
- [ ] [functions]
|
18
3-terrarium/3-intro-to-DOM-and-closures/.github/pre-lecture-quiz.md
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
*A warm-up quiz about the DOM*
|
||||
|
||||
Complete this quiz in class
|
||||
|
||||
1. The DOM stands for 'Document Object Management'
|
||||
|
||||
- [ ] [true]
|
||||
- [ ] [false]
|
||||
|
||||
2. The DOM can be thought of as a tree
|
||||
|
||||
- [ ] [true]
|
||||
- [ ] [false]
|
||||
|
||||
3. Using the Web API, you can manipulate the DOM
|
||||
|
||||
- [ ] [true]
|
||||
- [ ] [false]
|
21
3-terrarium/3-intro-to-DOM-and-closures/LICENSE
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2020 WebDev-For-Beginners
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
211
3-terrarium/3-intro-to-DOM-and-closures/README.md
Normal file
@@ -0,0 +1,211 @@
|
||||
# Terrarium Project Part 3: DOM Manipulation and a Closure
|
||||
|
||||

|
||||
> Sketchnote by [Tomomi Imura](https://twitter.com/girlie_mac)
|
||||
|
||||
## [Pre-lecture quiz](.github/pre-lecture-quiz.md)
|
||||
|
||||
### Introduction:
|
||||
|
||||
Manipulating the DOM, or the "Document Object Model", is a key aspect of web development. According to [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction), "The Document Object Model (DOM) is the data representation of the objects that comprise the structure and content of a document on the web." The challenges around DOM manipulation on the web have often been the impetus behind using JavaScript frameworks instead of vanilla JavaScript to manage the DOM, but we will manage on our own!
|
||||
|
||||
In addition, this lesson will introduce the idea of a [JavaScript closure](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures), which you can think of as a function enclosed by another function so that the inner function has access to the outer function's scope.
|
||||
|
||||
We will use a closure to manipulate the DOM.
|
||||
|
||||
> Think of the DOM as a tree, representing all the ways that a web page document can be manipulated. Various APIs (Application Program Interfaces) have been written so that programmers, using their programming language of choice, can access the DOM and edit, change, rearrange, and otherwise manage it.
|
||||
|
||||

|
||||
|
||||
> A representation of the DOM and the HTML markup that references it. From [Olfa Nasraoui](https://www.researchgate.net/publication/221417012_Profile-Based_Focused_Crawler_for_Social_Media-Sharing_Websites)
|
||||
|
||||
In this lesson, we will complete our interactive terrarium project by creating the JavaScript that will allow a user to manipulate the plants on the page.
|
||||
|
||||
### Prequisite:
|
||||
|
||||
You should have the HTML and CSS for your terrarium built. By the end of this lesson you will be able to move the plants into and out of the terrarium by dragging them.
|
||||
|
||||
### Task:
|
||||
|
||||
In your terrarium folder, create a new file called `script.js`. Import that file in the `<head>` section:
|
||||
|
||||
```html
|
||||
<script src="./script.js" defer></script>
|
||||
```
|
||||
|
||||
> Note: use `defer` when importing an external JavaScript file into the html file so as to allow the JavaScript to execute only after the HTML file has been fully loaded. You could also use the `async` attribute, which allows the script to execute while the HTML file is parsing, but in our case, it's important to have the HTML elements fully available for dragging before we allow the drag script to be executed.
|
||||
---
|
||||
|
||||
## 1. The DOM elements
|
||||
|
||||
The first thing you need to do is to create references to the elements that you want to manipulate in the DOM. In our case, they are the 14 plants currently waiting in the side bars.
|
||||
|
||||
### Task:
|
||||
|
||||
```html
|
||||
dragElement(document.getElementById('plant1'));
|
||||
dragElement(document.getElementById('plant2'));
|
||||
dragElement(document.getElementById('plant3'));
|
||||
dragElement(document.getElementById('plant4'));
|
||||
dragElement(document.getElementById('plant5'));
|
||||
dragElement(document.getElementById('plant6'));
|
||||
dragElement(document.getElementById('plant7'));
|
||||
dragElement(document.getElementById('plant8'));
|
||||
dragElement(document.getElementById('plant9'));
|
||||
dragElement(document.getElementById('plant10'));
|
||||
dragElement(document.getElementById('plant11'));
|
||||
dragElement(document.getElementById('plant12'));
|
||||
dragElement(document.getElementById('plant13'));
|
||||
dragElement(document.getElementById('plant14'));
|
||||
```
|
||||
|
||||
What's going on here? You are referencing the document and looking through its DOM to find an element with a particular Id. Remember in the first lesson on HTML that you gave individual Ids to each plant image (`id="plant1"`)? Now you will make use of that effort. After identifying each element, you pass that item to a function called `dragElement` that you'll build in a minute. Thus, the element in the HTML is now drag-enabled, or will be shortly.
|
||||
|
||||
✅ Why do we reference elements by Id? Why not by their CSS class? You might refer to the previous lesson on CSS to answer this question.
|
||||
|
||||
---
|
||||
|
||||
## 2. The Closure
|
||||
|
||||
Now you are ready to create the dragElement closure, which is an outer function that encloses an inner function or functions (in our case, we will have three).
|
||||
|
||||
Closures are useful when one or more functions need to access an outer function's scope. Here's an example:
|
||||
|
||||
```javascript
|
||||
function displayCandy(){
|
||||
let candy = ['jellybeans];
|
||||
function addCandy(candyType) {
|
||||
candy.push(candyType)
|
||||
}
|
||||
addCandy('gumdrops');
|
||||
}
|
||||
displayCandy();
|
||||
console.log(candy)
|
||||
```
|
||||
|
||||
In this example, the displayCandy function surrounds a function that pushes a new candy type into an array that already exists in the function. If you were to run this code, the `candy` array would be undefined, as it is a local variable (local to the closure).
|
||||
|
||||
✅ How can you make the `candy` array accessible? Try moving it outside the closure. This way, the array becomes global, rather than remaining only available to the closure's local scope.
|
||||
|
||||
### Task:
|
||||
|
||||
Under the element declarations in `script.js`, create a function:
|
||||
|
||||
```javascript
|
||||
function dragElement(terrariumElement) {
|
||||
//set 4 positions for positioning on the screen
|
||||
let pos1 = 0,
|
||||
pos2 = 0,
|
||||
pos3 = 0,
|
||||
pos4 = 0;
|
||||
terrariumElement.onpointerdown = pointerDrag;
|
||||
}
|
||||
```
|
||||
|
||||
`dragElement` get its `terrariumElement` object from the declarations at the top of the script. Then, you set some local positions at `0` for the object passed into the function. These are the local variables that will be manipulated for each element as you add drag and drop functionality within the closure to each element. The terrarium will be populated by these dragged elements, so the application needs to keep track of where they are placed.
|
||||
|
||||
In addition, the terrariumElement that is passed to this function is assigned a `pointerdown` event, which is part of the [web APIs](https://developer.mozilla.org/en-US/docs/Web/API) designed to help with DOM management. `onpointerdown` fires when a button is pushed, or in our case, a draggable element is touched. This event handler works on both [web and mobile browsers](https://caniuse.com/?search=onpointerdown), with a few exceptions.
|
||||
|
||||
✅ The [event handler `onclick`](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onclick) has much more support cross-browser; why wouldn't you use it here? Think about the exact type of screen interaction you're trying to create here.
|
||||
|
||||
---
|
||||
|
||||
## 3. The Pointerdrag function
|
||||
|
||||
The terrariumElement is ready to be dragged around; when the `onpointerdown` event is fired, the function pointerDrag is invoked. Add that function right under this line: `terrariumElement.onpointerdown = pointerDrag;`:
|
||||
|
||||
### Task:
|
||||
|
||||
```javascript
|
||||
function pointerDrag(e) {
|
||||
e.preventDefault();
|
||||
console.log(e);
|
||||
pos3 = e.clientX;
|
||||
pos4 = e.clientY;
|
||||
}
|
||||
```
|
||||
|
||||
Several things happen. First, you prevent the default events that normally happen on pointerdown from occurring by using `e.preventDefault();`. This way you have more control over the interface's behavior.
|
||||
|
||||
> Come back to this line when you've built the script file completely and try it without `e.preventDefault()` - what happens?
|
||||
|
||||
Second, open `index.html` in a browser window, and inspect the interface. When you click a plant, you can see how the 'e' event is captured. Dig into the event to see how much information is gathered by one pointer down event!
|
||||
|
||||
Next, note how the local variables `pos3` and `pos4` are set to e.clientX. You can find the `e` values in the inspection pane. These values capture the x and y coordinates of the plant at the moment you click on it or touch it. You will need fine-grained control over the behavior of the plants as you click and drag them, so you keep track of their coordinates.
|
||||
|
||||
✅ Is it becoming more clear why this entire app is built with one big closure? If it wasn't, how would you maintain scope for each of the 14 draggable plants?
|
||||
|
||||
Complete the initial function by adding two more pointer event manipulations under `pos4 = e.clientY`:
|
||||
|
||||
```html
|
||||
document.onpointermove = elementDrag;
|
||||
document.onpointerup = stopElementDrag;
|
||||
```
|
||||
Now you are indicating that you want the plant to be dragged along with the pointer as you move it, and for the dragging gesture to stop when you deselect the plant. `onpointermove` and `onpointerup` are all parts of the same API as `onpointerdown`. The interface will throw errors now as you have not yet defined the `elementDrag` and the `stopElementDrag` functions, so build those out next.
|
||||
|
||||
## 4. The elementDrag and stopElementDrag functions
|
||||
|
||||
You will complete your closure by adding two more internal functions that will handle what happens when you drag a plant and stop dragging it. The behavior you want is that you can drag any plant at any time and place it anywhere on the screen. This interface is quite un-opinionated (there is no drop zone for example) to allow you to design your terrarium exactly as you like it by adding, removing, and repositioning plants.
|
||||
|
||||
### Task:
|
||||
|
||||
Add the `elementDrag` function right after the closing curly bracket of `pointerDrag`:
|
||||
|
||||
```javascript
|
||||
function elementDrag(e) {
|
||||
pos1 = pos3 - e.clientX;
|
||||
pos2 = pos4 - e.clientY;
|
||||
pos3 = e.clientX;
|
||||
pos4 = e.clientY;
|
||||
console.log(pos1, pos2, pos3, pos4);
|
||||
terrariumElement.style.top = terrariumElement.offsetTop - pos2 + 'px';
|
||||
terrariumElement.style.left = terrariumElement.offsetLeft - pos1 + 'px';
|
||||
}
|
||||
```
|
||||
In this function, you do a lot of editing of the initial positions 1-4 that you set as local variables in the outer function. What's going on here?
|
||||
|
||||
As you drag, you reassign `pos1` by making it equal to `pos3` (which you set earlier as `e.clientX`) minus the current `e.clientX` value. You do a similar operation to `pos2`. Then, you reset `pos3` and `pos4` to the new X and Y coordinates of the element. You can watch these changes in the console as you drag. Then, you manipulate the plant's css style to set its new position based on the new positions of `pos1` and `pos2`, calculating the plant's top and left X and Y coordinates based on comparing its offset with these new positions.
|
||||
|
||||
> `offsetTop` and `offsetLeft` are CSS properties that set an element's position based on that of its parent; its parent can be any element that is not positioned as `static`.
|
||||
|
||||
All this recalculation of positioning allows you to fine-tune the behavior of the terrarium and its plants.
|
||||
|
||||
### Task:
|
||||
|
||||
The final task to complete the interface is to add the `closeElementDrag` function after the closing curly bracket of `elementDrag`:
|
||||
|
||||
```javascript
|
||||
function stopElementDrag() {
|
||||
document.onpointerup = null;
|
||||
document.onpointermove = null;
|
||||
}
|
||||
```
|
||||
|
||||
This small function resets the `onpointerup` and `onpointermove` events so that you can either restart your plant's progress by starting to drag it again, or start dragging a new plant.
|
||||
|
||||
✅ What happens if you don't set these events to null?
|
||||
|
||||
Now you have completed your project!
|
||||
|
||||
🥇Congratulations! You have finished your beautiful terrarium. 
|
||||
|
||||
---
|
||||
|
||||
## 🚀Challenge
|
||||
|
||||
Add new event handler to your closure to do something more to the plants; for example, double-click a plant to bring it to the front. Get creative!
|
||||
|
||||
## [Post-lecture quiz](.github/post-lecture-quiz.md)
|
||||
|
||||
## Review & Self Study
|
||||
|
||||
While dragging elements around the screen seems trivial, there are many ways to do this and many pitfalls, depending on the effect you seek. In fact, there is an entire [drag and drop API](https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API) that you can try. We didn't use it in this module because the effect we wanted was somewhat different, but try this API on your own project and see what you can achieve.
|
||||
|
||||
Find more information on pointer events on the [W3C docs](https://www.w3.org/TR/pointerevents1/) and on [MDN web docs](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events).
|
||||
|
||||
Always check browser capabilities using [CanIUse.com](https://caniuse.com/).
|
||||
|
||||
## Assignment
|
||||
|
||||
[Work a bit more with the DOM](assignment.md)
|
||||
|
11
3-terrarium/3-intro-to-DOM-and-closures/assignment.md
Normal file
@@ -0,0 +1,11 @@
|
||||
# Work a bit more with the DOM
|
||||
|
||||
## Instructions
|
||||
|
||||
Research the DOM a little more by 'adoping' a DOM element. Visit the MSDN's [list of DOM interfaces](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model) and pick one. Find it being used on a web site in the web, and write an explanation of how it is used.
|
||||
|
||||
## Rubric
|
||||
|
||||
| Criteria | Exemplary | Adequate | Needs Improvement |
|
||||
| -------- | --------------------------------------------- | ------------------------------------------------ | ----------------------- |
|
||||
| | Paragraph write-up is presented, with example | Paragraph write-up is presented, without example | No writeup is presented |
|
BIN
3-terrarium/3-intro-to-DOM-and-closures/images/dom-tree.png
Normal file
After Width: | Height: | Size: 44 KiB |
After Width: | Height: | Size: 888 KiB |
BIN
3-terrarium/3-intro-to-DOM-and-closures/images/webdev101-js.png
Normal file
After Width: | Height: | Size: 1.7 MiB |
@@ -0,0 +1,207 @@
|
||||
# Terrarium Project Part 3: DOM Manipulación y cierre
|
||||
|
||||
! [DOM y un cierre](images/webdev101-js.png)
|
||||
> Boceto de [Tomomi Imura](https://twitter.com/girlie_mac)
|
||||
|
||||
## [Pre-lecture prueba](.github/pre-lecture-quiz.md)
|
||||
|
||||
### Introducción:
|
||||
|
||||
Manipular el DOM, o el "Modelo de objetos de documento", es un aspecto clave del desarrollo web. Según [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction), "El modelo de objetos de documento (DOM) es la representación de datos de los objetos que componen la estructura y contenido de un documento en la web ". Los desafíos en torno a la manipulación de DOM en la web a menudo han sido el ímpetu detrás del uso de marcos de JavaScript en lugar de JavaScript vanilla para administrar el DOM, ¡pero lo administraremos por nuestra cuenta!
|
||||
|
||||
Además, esta lección presentará la idea de un [cierre de JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures), que puede considerar como una función encerrada por otra función para que la función interna tenga acceso al alcance de la función externa.
|
||||
|
||||
Usaremos un cierre para manipular el DOM.
|
||||
|
||||
> Piense en el DOM como un árbol, que representa todas las formas en que se puede manipular un documento de página web. Se han escrito varias API (interfaces de programas de aplicación) para que los programadores, utilizando el lenguaje de programación de su elección, puedan acceder al DOM y editarlo, cambiarlo, reorganizarlo y administrarlo de otro modo.
|
||||
|
||||
|
||||

|
||||
|
||||
> Una representación del DOM y el marcado HTML que lo hace referencia. De [Olfa Nasraoui](https://www.researchgate.net/publication/221417012_Profile-Based_Focused_Crawler_for_Social_Media-Sharing_Websites)
|
||||
|
||||
En esta lección, completaremos nuestro proyecto de terrario interactivo creando el JavaScript que permitirá al usuario manipular las plantas en la página.
|
||||
|
||||
### Requisito previo:
|
||||
|
||||
Debería tener el HTML y CSS para su terrario construido. Al final de esta lección, podrá mover las plantas dentro y fuera del terrario arrastrándolas.
|
||||
|
||||
### Tarea:
|
||||
|
||||
En su carpeta de terrario, cree un nuevo archivo llamado `script.js`. Importe ese archivo en la sección `<head>`:
|
||||
|
||||
|
||||
```html
|
||||
<script src="./script.js" defer></script>
|
||||
```
|
||||
|
||||
> Nota: use `defer` cuando importe un archivo JavaScript externo en el archivo html para permitir que JavaScript se ejecute solo después de que el archivo HTML se haya cargado por completo. También podría usar el atributo `async`, que permite que el script se ejecute mientras se analiza el archivo HTML, pero en nuestro caso, es importante tener los elementos HTML completamente disponibles para arrastrar antes de permitir que se ejecute el script de arrastre.
|
||||
---
|
||||
|
||||
## 1. Los elementos DOM
|
||||
|
||||
Lo primero que debe hacer es crear referencias a los elementos que desea manipular en el DOM. En nuestro caso, son las 14 plantas que esperan actualmente en las barras laterales.
|
||||
|
||||
|
||||
### Tarea:
|
||||
|
||||
```html
|
||||
dragElement(document.getElementById('plant1'));
|
||||
dragElement(document.getElementById('plant2'));
|
||||
dragElement(document.getElementById('plant3'));
|
||||
dragElement(document.getElementById('plant4'));
|
||||
dragElement(document.getElementById('plant5'));
|
||||
dragElement(document.getElementById('plant6'));
|
||||
dragElement(document.getElementById('plant7'));
|
||||
dragElement(document.getElementById('plant8'));
|
||||
dragElement(document.getElementById('plant9'));
|
||||
dragElement(document.getElementById('plant10'));
|
||||
dragElement(document.getElementById('plant11'));
|
||||
dragElement(document.getElementById('plant12'));
|
||||
dragElement(document.getElementById('plant13'));
|
||||
dragElement(document.getElementById('plant14'));
|
||||
```
|
||||
|
||||
¿Que está pasando aqui? Está haciendo referencia al documento y mirando a través de su DOM para encontrar un elemento con un Id particular. ¿Recuerda en la primera lección sobre HTML que le dio ID individuales a cada imagen de planta (`id = "plant1"`)? Ahora harás uso de ese esfuerzo. Después de identificar cada elemento, pasa ese elemento a una función llamada `dragElement` que creará en un minuto. Por lo tanto, el elemento en el HTML ahora está habilitado para arrastrar, o lo estará en breve.
|
||||
|
||||
✅ ¿Por qué hacemos referencia a elementos por Id? ¿Por qué no por su clase de CSS? Puede consultar la lección anterior sobre CSS para responder a esta pregunta.
|
||||
|
||||
---
|
||||
|
||||
## 2. El cierre
|
||||
|
||||
Ahora está listo para crear el cierre dragElement, que es una función externa que encierra una función o funciones internas (en nuestro caso, tendremos tres).
|
||||
|
||||
Los cierres son útiles cuando una o más funciones necesitan acceder al alcance de una función externa. He aquí un ejemplo:
|
||||
|
||||
```javascript
|
||||
function displayCandy(){
|
||||
let candy = ['jellybeans];
|
||||
function addCandy(candyType) {
|
||||
candy.push(candyType)
|
||||
}
|
||||
addCandy('gumdrops');
|
||||
}
|
||||
displayCandy();
|
||||
console.log(candy)
|
||||
```
|
||||
|
||||
En este ejemplo, la función displayCandy rodea una función que inserta un nuevo tipo de caramelo en una matriz que ya existe en la función. Si tuviera que ejecutar este código, la matriz `candy` no estaría definida, ya que es una variable local (local al cierre).
|
||||
|
||||
✅ ¿Cómo se puede hacer accesible la matriz de `candy`? Intente moverlo fuera del cierre. De esta manera, la matriz se vuelve global, en lugar de permanecer solo disponible para el alcance local del cierre.
|
||||
|
||||
### Tarea:
|
||||
|
||||
Debajo de las declaraciones de elementos en `script.js`, crea una función:
|
||||
|
||||
|
||||
```javascript
|
||||
function dragElement(terrariumElement) {
|
||||
//establecer 4 posiciones para posicionar en la pantalla
|
||||
let pos1 = 0,
|
||||
pos2 = 0,
|
||||
pos3 = 0,
|
||||
pos4 = 0;
|
||||
terrariumElement.onpointerdown = pointerDrag;
|
||||
}
|
||||
```
|
||||
|
||||
`dragElement` obtiene su objeto` terrariumElement` de las declaraciones en la parte superior del script. Luego, establece algunas posiciones locales en "0" para el objeto pasado a la función. Estas son las variables locales que se manipularán para cada elemento a medida que agrega la funcionalidad de arrastrar y soltar dentro del cierre de cada elemento. El terrario estará poblado por estos elementos arrastrados, por lo que la aplicación debe realizar un seguimiento de dónde se colocan.
|
||||
|
||||
Además, al terrariumElement que se pasa a esta función se le asigna un evento `pointerdown`, que forma parte de las [API web](https://developer.mozilla.org/en-US/docs/Web/API) diseñadas para ayudar con la gestión del DOM. `Onpointerdown` se dispara cuando se presiona un botón, o en nuestro caso, se toca un elemento que se puede arrastrar. Este controlador de eventos funciona tanto en [navegadores web como móviles](https://caniuse.com/?search=onpointerdown), con algunas excepciones.
|
||||
|
||||
✅ El [controlador de eventos `onclick`](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onclick) tiene mucho más soporte entre navegadores; ¿Por qué no lo usarías aquí? Piense en el tipo exacto de interacción de pantalla que está intentando crear aquí.
|
||||
|
||||
---
|
||||
|
||||
## 3. La función Pointerdrag
|
||||
|
||||
El terrariumElement está listo para ser arrastrado; cuando se dispara el evento `onpointerdown`, se invoca la función `pointerDrag`. Agrega esa función justo debajo de esta línea: `terrariumElement.onpointerdown = pointerDrag;`:
|
||||
|
||||
### Tarea:
|
||||
|
||||
```javascript
|
||||
function pointerDrag(e) {
|
||||
e.preventDefault();
|
||||
console.log(e);
|
||||
pos3 = e.clientX;
|
||||
pos4 = e.clientY;
|
||||
}
|
||||
```
|
||||
|
||||
Suceden varias cosas. Primero, evita que ocurran los eventos predeterminados que normalmente ocurren en el puntero hacia abajo usando `e.preventDefault ();`. De esta manera, tiene más control sobre el comportamiento de la interfaz.
|
||||
|
||||
> Regrese a esta línea cuando haya construido el archivo de script por completo y pruébelo sin `e.preventDefault ()`- ¿qué sucede?
|
||||
|
||||
En segundo lugar, abra `index.html` en una ventana del navegador e inspeccione la interfaz. Cuando hace clic en una planta, puede ver cómo se captura el evento 'e'. ¡Profundice en el evento para ver cuánta información recopila un evento de puntero hacia abajo!
|
||||
|
||||
A continuación, observe cómo las variables locales `pos3` y` pos4` se establecen en e.clientX. Puede encontrar los valores de `e` en el panel de inspección. Estos valores capturan las coordenadas xey de la planta en el momento en que hace clic en ella o la toca. Necesitará un control detallado sobre el comportamiento de las plantas al hacer clic en ellas y arrastrarlas, de modo que pueda realizar un seguimiento de sus coordenadas.
|
||||
|
||||
✅ ¿Está cada vez más claro por qué toda esta aplicación está construida con un gran cierre? Si no fuera así, ¿cómo mantendría el alcance para cada una de las 14 plantas arrastrables?
|
||||
|
||||
Complete la función inicial agregando dos manipulaciones de eventos de puntero más en `pos4 = e.clientY`:
|
||||
|
||||
```html
|
||||
document.onpointermove = elementDrag;
|
||||
document.onpointerup = stopElementDrag;
|
||||
```
|
||||
Ahora está indicando que desea que la planta se arrastre junto con el puntero mientras la mueve, y que el gesto de arrastre se detenga cuando anule la selección de la planta. `Onpointermove` y `onpointerup` son partes de la misma API que `onpointerdown`. La interfaz arrojará errores ahora ya que aún no ha definido las funciones `elementDrag` y `stopElementDrag`, así que compárelas a continuación.
|
||||
|
||||
## 4. Las funciones elementDrag y stopElementDrag
|
||||
|
||||
Completarás tu cierre agregando dos funciones internas más que se encargarán de lo que sucede cuando arrastras una planta y dejas de arrastrarla. El comportamiento que desea es que pueda arrastrar cualquier planta en cualquier momento y colocarla en cualquier lugar de la pantalla. Esta interfaz no tiene opiniones (no hay zona de caída, por ejemplo) para permitirle diseñar su terrario exactamente como le gusta agregando, quitando y reposicionando plantas.
|
||||
|
||||
### Tarea:
|
||||
|
||||
Agrega la función `elementDrag` justo después del corchete de cierre de `pointerDrag`:
|
||||
|
||||
```javascript
|
||||
function elementDrag(e) {
|
||||
pos1 = pos3 - e.clientX;
|
||||
pos2 = pos4 - e.clientY;
|
||||
pos3 = e.clientX;
|
||||
pos4 = e.clientY;
|
||||
console.log(pos1, pos2, pos3, pos4);
|
||||
terrariumElement.style.top = terrariumElement.offsetTop - pos2 + 'px';
|
||||
terrariumElement.style.left = terrariumElement.offsetLeft - pos1 + 'px';
|
||||
}
|
||||
```
|
||||
En esta función, usted edita mucho las posiciones iniciales 1-4 que establece como variables locales en la función externa. ¿Que está pasando aqui?
|
||||
|
||||
A medida que arrastra, reasigna `pos1` haciéndolo igual a `pos3` (que configuró anteriormente como `e.clientX`) menos el valor actual de `e.clientX`. Realiza una operación similar a `pos2`. Luego, restablece `pos3` y `pos4` a las nuevas coordenadas X e Y del elemento. Puede ver estos cambios en la consola mientras arrastra. Luego, manipula el estilo CSS de la planta para establecer su nueva posición en función de las nuevas posiciones de `pos1` y` pos2`, calculando las coordenadas X e Y superior e izquierda de la planta en función de la comparación de su desplazamiento con estas nuevas posiciones.
|
||||
|
||||
> `OffsetTop` y `offsetLeft` son propiedades CSS que establecen la posición de un elemento basándose en la de su padre; su padre puede ser cualquier elemento que no esté posicionado como "estático".
|
||||
|
||||
Todo este recálculo de posicionamiento le permite afinar el comportamiento del terrario y sus plantas.
|
||||
|
||||
### Tarea:
|
||||
|
||||
La tarea final para completar la interfaz es agregar la función `closeElementDrag` después del corchete de cierre de `elementDrag`:
|
||||
|
||||
```javascript
|
||||
function stopElementDrag() {
|
||||
document.onpointerup = null;
|
||||
document.onpointermove = null;
|
||||
}
|
||||
```
|
||||
|
||||
Esta pequeña función restablece los eventos `onpointerup` y `onpointermove` para que pueda reiniciar el progreso de su planta comenzando a arrastrarla nuevamente, o comenzar a arrastrar una nueva planta.
|
||||
|
||||
✅ ¿Qué sucede si no configura estos eventos como nulos?
|
||||
|
||||
¡Ahora has completado tu proyecto!
|
||||
|
||||
---
|
||||
|
||||
🥇¡Felicitaciones! Has terminado tu hermoso terrario. 
|
||||
|
||||
🚀Challenge: agregue un nuevo controlador de eventos a su cierre para hacer algo más en las plantas; por ejemplo, haga doble clic en una planta para traerla al frente. ¡Se creativo!
|
||||
|
||||
## [Post-lecture prueba](.github/post-lecture-quiz.md)
|
||||
|
||||
## Revisión y autoestudio
|
||||
|
||||
Si bien arrastrar elementos por la pantalla parece trivial, hay muchas formas de hacerlo y muchas trampas, según el efecto que busque. De hecho, hay una [API de arrastrar y soltar](https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API) completa que puedes probar. No lo usamos en este módulo porque el efecto que queríamos era algo diferente, pero pruebe esta API en su propio proyecto y vea lo que puede lograr.
|
||||
|
||||
** Tarea: [Trabajar un poco más con el DOM](assignment.md)
|
||||
|
@@ -0,0 +1,11 @@
|
||||
# Trabaja un poco más con DOM
|
||||
|
||||
## Instrucciones
|
||||
|
||||
Investigue el DOM un poco más 'adoptando' un elemento DOM. Visite la [lista de interfaces DOM de MSDN](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model) y elija una. Encuéntrelo en un sitio web en la web y escriba una explicación de cómo se usa.
|
||||
|
||||
## Rúbrica
|
||||
|
||||
| Criterios | Ejemplar | Adecuado | Necesita mejorar |
|
||||
| -------- | --------------------------------------------- | ------------------------------------------------ | ----------------------- |
|
||||
| | Se presenta la redacción del párrafo, con ejemplo | Se presenta la redacción del párrafo, sin ejemplo | No se presenta ninguna reseña |
|
21
3-terrarium/LICENSE
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2020 WebDev-For-Beginners
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
34
3-terrarium/README.md
Normal file
@@ -0,0 +1,34 @@
|
||||
# My Terrarium: A project to learn about HTML, CSS, and DOM manipulation using JavaScript 🌵🌱
|
||||
|
||||
A small drag and drop code-meditation. With a little HTML, JS and CSS, you can build a web interface, style it, and add an interaction.
|
||||
|
||||

|
||||
|
||||
# Lessons
|
||||
|
||||
1. [Intro to HTML](./1-intro-to-html/README.md)
|
||||
2. [Intro to CSS](./2-intro-to-css/README.md)
|
||||
3. [Intro to DOM and JS Closures](./3-intro-to-DOM-and-closures/README.md)
|
||||
|
||||
## Credits
|
||||
|
||||
Written with ♥️ by [Jen Looper](https://www.twitter.com/jenlooper)
|
||||
|
||||
The terrarium created via CSS was inspired by Jakub Mandra's glass jar [codepen](https://codepen.io/Rotarepmi/pen/rjpNZY).
|
||||
|
||||
The artwork was hand drawn by [Jen Looper](http://jenlooper.com) using Procreate.
|
||||
|
||||
## Deploy your Terrarium
|
||||
|
||||
You can deploy, or publish your terrarium to the web using Azure Static Web Apps.
|
||||
|
||||
1. Fork this repo
|
||||
|
||||
2. Press this button
|
||||
|
||||
[](https://portal.azure.com/?feature.customportal=false&WT.mc_id=terrarium-github-webdevforbeginners#create/Microsoft.StaticApp)
|
||||
|
||||
3. Walk through the wizard creating your app. Make sure you set the app root to either be `/solution` or the root of your codebase. There's no API in this app, so don't worry about adding that. A .github folder will be created in your forked repo that will help Azure Static Web Apps' build service build and publish your app to a new URL.
|
||||
|
||||
|
||||
|
BIN
3-terrarium/images/screenshot_gray.png
Normal file
After Width: | Height: | Size: 888 KiB |
BIN
3-terrarium/solution/images/plant1.png
Normal file
After Width: | Height: | Size: 60 KiB |
BIN
3-terrarium/solution/images/plant10.png
Normal file
After Width: | Height: | Size: 127 KiB |
BIN
3-terrarium/solution/images/plant11.png
Normal file
After Width: | Height: | Size: 147 KiB |
BIN
3-terrarium/solution/images/plant12.png
Normal file
After Width: | Height: | Size: 60 KiB |
BIN
3-terrarium/solution/images/plant13.png
Normal file
After Width: | Height: | Size: 170 KiB |
BIN
3-terrarium/solution/images/plant14.png
Normal file
After Width: | Height: | Size: 168 KiB |
BIN
3-terrarium/solution/images/plant2.png
Normal file
After Width: | Height: | Size: 109 KiB |
BIN
3-terrarium/solution/images/plant3.png
Normal file
After Width: | Height: | Size: 83 KiB |
BIN
3-terrarium/solution/images/plant4.png
Normal file
After Width: | Height: | Size: 97 KiB |
BIN
3-terrarium/solution/images/plant5.png
Normal file
After Width: | Height: | Size: 74 KiB |
BIN
3-terrarium/solution/images/plant6.png
Normal file
After Width: | Height: | Size: 75 KiB |
BIN
3-terrarium/solution/images/plant7.png
Normal file
After Width: | Height: | Size: 126 KiB |
BIN
3-terrarium/solution/images/plant8.png
Normal file
After Width: | Height: | Size: 175 KiB |
BIN
3-terrarium/solution/images/plant9.png
Normal file
After Width: | Height: | Size: 122 KiB |
76
3-terrarium/solution/index.html
Normal file
@@ -0,0 +1,76 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>Welcome to my Virtual Terrarium</title>
|
||||
<meta charset="utf-8" />
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<!-- import the webpage's stylesheet -->
|
||||
<link rel="stylesheet" href="./style.css" />
|
||||
<!-- import the webpage's JavaScript file -->
|
||||
<script src="./script.js" defer></script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="page">
|
||||
<h1>My Terrarium</h1>
|
||||
|
||||
<div id="left-container" class="container">
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant1" src="./images/plant1.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant2" src="./images/plant2.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant3" src="./images/plant3.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant4" src="./images/plant4.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant5" src="./images/plant5.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant6" src="./images/plant6.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant7" src="./images/plant7.png" />
|
||||
</div>
|
||||
</div>
|
||||
<div id="right-container" class="container">
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant8" src="./images/plant8.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant9" src="./images/plant9.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant10" src="./images/plant10.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant11" src="./images/plant11.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant12" src="./images/plant12.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant13" src="./images/plant13.png" />
|
||||
</div>
|
||||
<div class="plant-holder">
|
||||
<img class="plant" alt="plant" id="plant14" src="./images/plant14.png" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="terrarium">
|
||||
<div class="jar-top"></div>
|
||||
<div class="jar-walls">
|
||||
<div class="jar-glossy-long"></div>
|
||||
<div class="jar-glossy-short"></div>
|
||||
</div>
|
||||
<div class="dirt"></div>
|
||||
<div class="jar-bottom"></div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
64
3-terrarium/solution/script.js
Normal file
@@ -0,0 +1,64 @@
|
||||
/*The solution to draggable elements was inspired by w3schools solution on creating a [Draggable HTML Element](https://www.w3schools.com/howto/howto_js_draggable.asp).*/
|
||||
|
||||
dragElement(document.getElementById('plant1'));
|
||||
dragElement(document.getElementById('plant2'));
|
||||
dragElement(document.getElementById('plant3'));
|
||||
dragElement(document.getElementById('plant4'));
|
||||
dragElement(document.getElementById('plant5'));
|
||||
dragElement(document.getElementById('plant6'));
|
||||
dragElement(document.getElementById('plant7'));
|
||||
dragElement(document.getElementById('plant8'));
|
||||
dragElement(document.getElementById('plant9'));
|
||||
dragElement(document.getElementById('plant10'));
|
||||
dragElement(document.getElementById('plant11'));
|
||||
dragElement(document.getElementById('plant12'));
|
||||
dragElement(document.getElementById('plant13'));
|
||||
dragElement(document.getElementById('plant14'));
|
||||
|
||||
/*"A closure is the combination of a function bundled together (enclosed)
|
||||
with references to its surrounding state (the lexical environment).
|
||||
In other words, a closure gives you access to an outer function’s scope
|
||||
from an inner function." Create a closure so that you can track the dragged element*/
|
||||
|
||||
function dragElement(terrariumElement) {
|
||||
//set 4 positions for positioning on the screen
|
||||
let pos1 = 0,
|
||||
pos2 = 0,
|
||||
pos3 = 0,
|
||||
pos4 = 0;
|
||||
terrariumElement.onpointerdown = pointerDrag;
|
||||
|
||||
function pointerDrag(e) {
|
||||
e.preventDefault();
|
||||
console.log(e);
|
||||
// get the initial mouse cursor position for pos3 and pos4
|
||||
pos3 = e.clientX;
|
||||
pos4 = e.clientY;
|
||||
// when the mouse moves, start the drag
|
||||
document.onpointermove = elementDrag;
|
||||
// when the mouse is lifted, stop the drag
|
||||
document.onpointerup = stopElementDrag;
|
||||
}
|
||||
|
||||
function elementDrag(e) {
|
||||
// calculate the new cursor position
|
||||
// pos1 = where the Xmouse WAS - where it IS
|
||||
pos1 = pos3 - e.clientX;
|
||||
// pos2 = where the Ymouse WAS - where it IS
|
||||
pos2 = pos4 - e.clientY;
|
||||
//reset pos3 to current location of Xmouse
|
||||
pos3 = e.clientX;
|
||||
//reset pos4 to current location of Ymouse
|
||||
pos4 = e.clientY;
|
||||
console.log(pos1, pos2, pos3, pos4);
|
||||
// set the element's new position:
|
||||
terrariumElement.style.top = terrariumElement.offsetTop - pos2 + 'px';
|
||||
terrariumElement.style.left = terrariumElement.offsetLeft - pos1 + 'px';
|
||||
}
|
||||
|
||||
function stopElementDrag() {
|
||||
// stop calculating when mouse is released
|
||||
document.onpointerup = null;
|
||||
document.onpointermove = null;
|
||||
}
|
||||
}
|
105
3-terrarium/solution/style.css
Normal file
@@ -0,0 +1,105 @@
|
||||
body {
|
||||
font-family: helvetica, arial, sans-serif;
|
||||
}
|
||||
|
||||
h1 {
|
||||
color: #3a241d;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
#left-container {
|
||||
left: 0px;
|
||||
}
|
||||
|
||||
#right-container {
|
||||
right: 0px;
|
||||
}
|
||||
|
||||
.container {
|
||||
background-color: #eee;
|
||||
width: 15%;
|
||||
top: 0px;
|
||||
position: absolute;
|
||||
height: 100%;
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
.plant-holder {
|
||||
position: relative;
|
||||
height: 13%;
|
||||
left: -10px;
|
||||
}
|
||||
|
||||
.plant {
|
||||
position: absolute;
|
||||
max-width: 150%;
|
||||
max-height: 150%;
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
/*https://codepen.io/Rotarepmi/pen/rjpNZY*/
|
||||
|
||||
.jar-walls {
|
||||
height: 80%;
|
||||
width: 60%;
|
||||
background: #d1e1df;
|
||||
border-radius: 10%;
|
||||
position: absolute;
|
||||
bottom: 0.5%;
|
||||
left: 20%;
|
||||
opacity: 0.5;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.jar-top {
|
||||
width: 50%;
|
||||
height: 5%;
|
||||
background: #d1e1df;
|
||||
position: absolute;
|
||||
bottom: 80.5%;
|
||||
left: 25%;
|
||||
opacity: 0.7;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.jar-bottom {
|
||||
width: 50%;
|
||||
height: 1%;
|
||||
background: #d1e1df;
|
||||
position: absolute;
|
||||
bottom: 0%;
|
||||
left: 25%;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.dirt {
|
||||
width: 58%;
|
||||
height: 5%;
|
||||
background: #3a241d;
|
||||
position: absolute;
|
||||
border-radius: 0 0 4rem 4rem;
|
||||
bottom: 1%;
|
||||
left: 21%;
|
||||
opacity: 0.7;
|
||||
z-index: -1;
|
||||
}
|
||||
|
||||
.jar-glossy-long {
|
||||
width: 3%;
|
||||
height: 20%;
|
||||
border-radius: 2rem;
|
||||
background: #ddfbff;
|
||||
position: absolute;
|
||||
bottom: 20%;
|
||||
left: 5%;
|
||||
}
|
||||
|
||||
.jar-glossy-short {
|
||||
width: 3%;
|
||||
height: 5%;
|
||||
border-radius: 2rem;
|
||||
background: #ddfbff;
|
||||
position: absolute;
|
||||
bottom: 45%;
|
||||
left: 5%;
|
||||
}
|
27
3-terrarium/translations/README.es.md
Normal file
@@ -0,0 +1,27 @@
|
||||
# Mi terrario: un proyecto para aprender sobre la manipulación de HTML, CSS y DOM usando JavaScript 🌵🌱
|
||||
|
||||
Una pequeña meditación de código de arrastrar y soltar. Con un poco de HTML, JS y CSS, puede crear una interfaz web, darle estilo y agregar una interacción.
|
||||
|
||||

|
||||
|
||||
# Lessons
|
||||
|
||||
1. [Introducción a CSS](./intro-to-css/README.md)
|
||||
2. [Introducción a HTML](./intro-to-html/README.md)
|
||||
3. [Introducción a DOM y JS Closures](intro-to-DOM-and-js-closures/README.md)
|
||||
|
||||
## Créditos
|
||||
|
||||
Escrito con ♥ ️ por [Jen Looper](https://www.twitter.com/jenlooper)
|
||||
|
||||
El terrario creado a través de CSS se inspiró en el frasco de vidrio [codepen](https://codepen.io/Rotarepmi/pen/rjpNZY) de Jakub Mandra.
|
||||
|
||||
La obra de arte fue dibujada a mano por [Jen Looper](http://jenlooper.com) usando Procreate.
|
||||
|
||||
La solución para elementos arrastrables se inspiró en la solución de w3schools para crear un [Elemento HTML arrastrable](https://www.w3schools.com/howto/howto_js_draggable.asp).
|
||||
|
||||
Encuentre más información sobre eventos de punteros en los [documentos del W3C](https://www.w3.org/TR/pointerevents1/) y en los [documentos web de MDN](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events).
|
||||
|
||||
Siempre verifique las capacidades del navegador usando [CanIUse.com](https://caniuse.com/).
|
||||
|
||||
Obtenga más información sobre cómo crear sitios para la Web y dispositivos móviles en [Microsoft Learn](https://docs.microsoft.com/learn/modules/build-simple-website/?WT.mc_id=webdev101-github-jelooper).
|