Skip to content

Commit 06417d2

Browse files
authored
Merge pull request #330 from Leired7/Scrolling
Scrolling
2 parents e643861 + e1c887a commit 06417d2

File tree

6 files changed

+75
-75
lines changed

6 files changed

+75
-75
lines changed

2-ui/3-event-details/8-onscroll/1-endless-page/solution.md

Lines changed: 24 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,63 +1,63 @@
1-
The core of the solution is a function that adds more dates to the page (or loads more stuff in real-life) while we're at the page end.
1+
El núcleo de la solución es una función que añade más fechas a la página (o carga más cosas en la vida real) mientras estamos en el final de la página.
22

3-
We can call it immediately and add as a `window.onscroll` handler.
3+
Podemos llamarlo inmediatamente o agregarlo como un manejador de `window.onscroll`.
44

5-
The most important question is: "How do we detect that the page is scrolled to bottom?"
5+
La pregunta más importante es: "¿Cómo detectamos que la página se desplaza hasta el fondo?"
66

7-
Let's use window-relative coordinates.
7+
Usaremos las coordenadas de la ventana.
88

9-
The document is represented (and contained) within `<html>` tag, that is `document.documentElement`.
9+
El documento está representado (y contenido) dentro de la etiqueta `<html>`, que es `document.documentElement`.
1010

11-
We can get window-relative coordinates of the whole document as `document.documentElement.getBoundingClientRect()`, the `bottom` property will be window-relative coordinate of the document bottom.
11+
Podemos obtener las coordenadas relativas a la ventana de todo el documento como `document.documentElement.getBoundingClientRect()`, la propiedad `bottom` será la coordenada relativa a la ventana del fondo del documento.
1212

13-
For instance, if the height of the whole HTML document is `2000px`, then:
13+
Por ejemplo, si la altura de todo el documento es `2000px`, entonces:
1414

1515
```js
16-
// when we're on the top of the page
17-
// window-relative top = 0
16+
// cuando estamos en la parte superior de la página
17+
// window-relative top = 0 (relativo a la ventana, límite superior = 0 )
1818
document.documentElement.getBoundingClientRect().top = 0
1919

20-
// window-relative bottom = 2000
21-
// the document is long, so that is probably far beyond the window bottom
20+
// window-relative bottom = 2000 (relativo a la ventana, límite inferior = 2000)
21+
// el documento es largo, así que probablemente esté más allá del fondo de la ventana
2222
document.documentElement.getBoundingClientRect().bottom = 2000
2323
```
2424

25-
If we scroll `500px` below, then:
25+
Si nos desplazamos `500px` abajo, entonces:
2626

2727
```js
28-
// document top is above the window 500px
28+
// la parte superior del documento está 500px por encima de la ventana
2929
document.documentElement.getBoundingClientRect().top = -500
30-
// document bottom is 500px closer
30+
// la parte inferior del documento está 500px más cerca
3131
document.documentElement.getBoundingClientRect().bottom = 1500
3232
```
3333

34-
When we scroll till the end, assuming that the window height is `600px`:
34+
Cuando nos desplazamos hasta el final, asumiendo que la altura de la venta es `600px`:
3535

3636

3737
```js
38-
// document top is above the window 1400px
38+
// La parte superior del documento está 1400px sobre la ventana
3939
document.documentElement.getBoundingClientRect().top = -1400
40-
// document bottom is below the window 600px
40+
// la parte inferior del documento está a 600px debajo de la ventana
4141
document.documentElement.getBoundingClientRect().bottom = 600
4242
```
4343

44-
Please note that the `bottom` can't be `0`, because it never reaches the window top. The lowest limit of the `bottom` coordinate is the window height (we assumed it to be `600`), we can't scroll it any more up.
44+
Tened en cuenta que el fondo del documento `bottom` nunca puede ser `0`, porque nunca llega a la parte superior de la ventana. El límite más bajo de la coordenada `bottom` es la altura de la ventana (asumimos que es `600`), no podemos desplazarla más hacia arriba.
4545

46-
We can obtain the window height as `document.documentElement.clientHeight`.
46+
Podemos obtener la altura de la ventana con `document.documentElement.clientHeight`.
4747

48-
For our task, we need to know when the document bottom is not no more than `100px` away from it (that is: `600-700px`, if the height is `600`).
48+
Para nuestra tarea, necesitamos saber cuando tenemos el final del documento a unos `100px` (esto es: `600-700px`, si la altura es de `600`).
4949

50-
So here's the function:
50+
Así que aquí está la función:
5151

5252
```js
5353
function populate() {
5454
while(true) {
55-
// document bottom
55+
// final del documento
5656
let windowRelativeBottom = document.documentElement.getBoundingClientRect().bottom;
5757

58-
// if the user scrolled far enough (<100px to the end)
58+
// si el usuario se desplaza lo suficiente (<100px hasta el final)
5959
if (windowRelativeBottom < document.documentElement.clientHeight + 100) {
60-
// let's add more data
60+
// vamos añadir más datos
6161
document.body.insertAdjacentHTML("beforeend", `<p>Date: ${new Date()}</p>`);
6262
}
6363
}

2-ui/3-event-details/8-onscroll/1-endless-page/task.md

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,19 @@ importance: 5
22

33
---
44

5-
# Endless page
5+
# Página sin fin
66

7-
Create an endless page. When a visitor scrolls it to the end, it auto-appends current date-time to the text (so that a visitor can scroll more).
7+
Crear una página interminable. Cuando un visitante la desplace hasta el final, se auto-añadirá la fecha y hora actual al texto (así el visitante podrá seguir desplazándose)
88

9-
Like this:
9+
Así:
1010

1111
[iframe src="solution" height=200]
1212

13-
Please note two important features of the scroll:
13+
Por favor tenga en cuenta dos características importantes del desplazamiento:
1414

15-
1. **The scroll is "elastic".** We can scroll a little beyond the document start or end in some browsers/devices (empty space below is shown, and then the document will automatically "bounces back" to normal).
16-
2. **The scroll is imprecise.** When we scroll to page end, then we may be in fact like 0-50px away from the real document bottom.
15+
1. **El scroll es "elástico".** En algunos navegadores/dispositivos podemos desplazarnos un poco más allá del inicio o final del documento (se muestra un espacio vacío abajo, y luego el documento "rebota" automáticamente a la normalidad).
16+
2. **El scroll es impreciso.** Cuando nos desplazamos hasta el final de la página, podemos estar de hecho como a 0-50px del fondo del documento real.
1717

18-
So, "scrolling to the end" should mean that the visitor is no more than 100px away from the document end.
18+
Así que, "desplazarse hasta el final" debería significar que el visitante no está a más de 100px del final del documento.
1919

20-
P.S. In real life we may want to show "more messages" or "more goods".
20+
P.D. En la vida real podemos querer mostrar "más mensajes" o "más bienes".

2-ui/3-event-details/8-onscroll/2-updown-button/task.md

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,15 @@ importance: 5
22

33
---
44

5-
# Up/down button
5+
# Botón para subir/bajar
66

7-
Create a "to the top" button to help with page scrolling.
7+
Crea un botón "ir arriba" para ayudar con el desplazamiento de la página.
88

9-
It should work like this:
10-
- While the page is not scrolled down at least for the window height -- it's invisible.
11-
- When the page is scrolled down more than the window height -- there appears an "upwards" arrow in the left-top corner. If the page is scrolled back, it disappears.
12-
- When the arrow is clicked, the page scrolls to the top.
9+
Debería funcionar así:
10+
- Mientras que la página no se desplace hacia abajo al menos la altura de la ventana... es invisible.
11+
- Cuando la página se desplaza hacia abajo más que la altura de la ventana -- aparece una flecha "hacia arriba" en la esquina superior izquierda. Si la página se desplaza hacia atrás desaparece.
12+
- Cuando se hace click en la flecha, la página se desplaza hacia arriba hasta el tope.
1313

14-
Like this (top-left corner, scroll to see):
14+
Así (esquina superior izquierda, desplácese para ver):
1515

1616
[iframe border="1" height="200" link src="solution"]

2-ui/3-event-details/8-onscroll/3-load-visible-img/solution.md

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,31 @@
1-
The `onscroll` handler should check which images are visible and show them.
1+
El manejador `onscroll` debería comprobar qué imágenes son visibles y mostrarlas.
22

3-
We also want to run it when the page loads, to detect immediately visible images and load them.
3+
También queremos que se ejecute cuando se cargue la página, para detectar las imágenes visibles inmediatamente y cargarlas.
44

5-
The code should execute when the document is loaded, so that it has access to its content.
5+
El código debería ejecutarse cuando se cargue el documento, para que tenga acceso a su contenido.
66

7-
Or put it at the `<body>` bottom:
7+
O ponerlo en la parte inferior del `<body>`:
88

99
```js
10-
// ...the page content is above...
10+
// ...el contenido de la página está arriba...
1111

1212
function isVisible(elem) {
1313

1414
let coords = elem.getBoundingClientRect();
1515

1616
let windowHeight = document.documentElement.clientHeight;
1717

18-
// top elem edge is visible?
18+
// ¿El borde superior del elemento es visible?
1919
let topVisible = coords.top > 0 && coords.top < windowHeight;
2020

21-
// bottom elem edge is visible?
21+
// ¿El borde inferior del elemento es visible?
2222
let bottomVisible = coords.bottom < windowHeight && coords.bottom > 0;
2323

2424
return topVisible || bottomVisible;
2525
}
2626
```
2727

28-
The `showVisible()` function uses the visibility check, implemented by `isVisible()`, to load visible images:
28+
La función `showVisible()` utiliza el control de visibilidad, implementado por `isVisible()`, para cargar imágenes visibles:
2929

3030
```js
3131
function showVisible() {
@@ -46,4 +46,4 @@ window.onscroll = showVisible;
4646
*/!*
4747
```
4848

49-
P.S. The solution also has a variant of `isVisible` that "preloads" images that are within 1 page above/below the current document scroll.
49+
P.D. La solución tiene una variante de `isVisible` que "precarga" imágenes que están dentro de 1 página por encima/debajo del desplazamiento del documento actual.

2-ui/3-event-details/8-onscroll/3-load-visible-img/task.md

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,29 +2,29 @@ importance: 4
22

33
---
44

5-
# Load visible images
5+
# Cargar imágenes visibles
66

7-
Let's say we have a slow-speed client and want to save their mobile traffic.
7+
Digamos que tenemos un cliente con baja velocidad de conexión y queremos cuidar su tarifa de datos.
88

9-
For that purpose we decide not to show images immediately, but rather replace them with placeholders, like this:
9+
Para ello decidimos no mostrar las imágenes inmediatemente, sino sustituirlas por marcadores de posición, como este:
1010

1111
```html
1212
<img *!*src="placeholder.svg"*/!* width="128" height="128" *!*data-src="real.jpg"*/!*>
1313
```
1414

15-
So, initially all images are `placeholder.svg`. When the page scrolls to the position where the user can see the image -- we change `src` to the one in `data-src`, and so the image loads.
15+
Así que, inicialmente todas las imágenes son `placeholder.svg`. Cuando la página se desplaza a la posición donde el usuario puede ver la imagen -- cambiamos `src` a `data-src`, y así la imagen se carga.
1616

17-
Here's an example in `iframe`:
17+
Aquí hay un ejemplo en `iframe`:
1818

1919
[iframe src="solution"]
2020

21-
Scroll it to see images load "on-demand".
21+
Desplázate para ver las imagenes cargadas "bajo demanda".
2222

23-
Requirements:
24-
- When the page loads, those images that are on-screen should load immediately, prior to any scrolling.
25-
- Some images may be regular, without `data-src`. The code should not touch them.
26-
- Once an image is loaded, it should not reload any more when scrolled in/out.
23+
Requerimientos:
24+
- Cuando la página se carga, las imágenes que están en pantalla deben cargarse inmediatamente, antes de cualquier desplazamiento.
25+
- Algunas imágenes pueden ser regulares, sin `data-src`. El código no debe tocarlas.
26+
- Una vez que una imagen se carga, no debe recargarse más cuando haya desplazamiento arriba/abajo.
2727

28-
P.S. If you can, make a more advanced solution that would "preload" images that are one page below/after the current position.
28+
P.D. Si puedes, haz una solución más avanzada para "precargar" las imágenes que están más abajo/después de la posición actual.
2929

30-
P.P.S. Only vertical scroll is to be handled, no horizontal scrolling.
30+
Post P.D. Sólo se debe manejar el desplazamiento vertical, no el horizontal.
Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
1-
# Scrolling
1+
# Desplazamiento
22

3-
The `scroll` event allows to react on a page or element scrolling. There are quite a few good things we can do here.
3+
El evento `scroll` permite reaccionar al desplazamiento de una página o elemento. Hay bastantes cosas buenas que podemos hacer aquí.
44

5-
For instance:
6-
- Show/hide additional controls or information depending on where in the document the user is.
7-
- Load more data when the user scrolls down till the end of the page.
5+
Por ejemplo:
6+
- Mostrar/ocultar controles o información adicional según el lugar del documento en el que se encuentre el/la usuario/a.
7+
- Cargar más datos cuando el/la usuario/a se desplaza hacia abajo hasta el final del documento.
88

9-
Here's a small function to show the current scroll:
9+
Aquí hay una pequeña función para mostrar el desplazamiento actual:
1010

1111
```js autorun
1212
window.addEventListener('scroll', function() {
@@ -17,21 +17,21 @@ window.addEventListener('scroll', function() {
1717
```online
1818
In action:
1919
20-
Current scroll = <b id="showScroll">scroll the window</b>
20+
Desplazamiento actual = <b id="showScroll">Desplazamiento de la ventana</b>
2121
```
2222

23-
The `scroll` event works both on the `window` and on scrollable elements.
23+
El evento `scroll` funciona tanto en `window` como en los elementos desplazables.
2424

25-
## Prevent scrolling
25+
## Evitar el desplazamiento
2626

27-
How do we make something unscrollable?
27+
¿Qué hacemos para que algo no se pueda desplazar?
2828

29-
We can't prevent scrolling by using `event.preventDefault()` in `onscroll` listener, because it triggers *after* the scroll has already happened.
29+
No podemos evitar el desplazamiento utilizando `event.preventDefault()` oyendo al evento `onscroll`, porque este se activa *después* de que el desplazamiento haya ocurrido.
3030

31-
But we can prevent scrolling by `event.preventDefault()` on an event that causes the scroll, for instance `keydown` event for `key:pageUp` and `key:pageDown`.
31+
Pero podemos prevenir el desplazamiento con `event.preventDefault()` en un evento que cause el desplazamiento, por ejemplo en el evento `keydown` para `key:pageUp` y `key:pageDown`.
3232

33-
If we add an event handler to these events and `event.preventDefault()` in it, then the scroll won't start.
33+
Si añadimos un manejador de eventos a estos eventos y un `event.preventDefault()` en el manejador, entonces el desplazamiento no se iniciará.
3434

35-
There are many ways to initiate a scroll, so it's more reliable to use CSS, `overflow` property.
35+
Hay muchas maneras de iniciar un desplazamiento, la más fiable es usar CSS, la propiedad `overflow`.
3636

37-
Here are few tasks that you can solve or look through to see the applications on `onscroll`.
37+
Aquí hay algunas tareas que puedes resolver o mirar para ver las aplicaciones de `onscroll`.

0 commit comments

Comments
 (0)