Skip to content

Element size and scrolling #433

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
49 commits
Select commit Hold shift + click to select a range
18a2e99
Update solution.md
lgabrielvleon Oct 20, 2020
ba5c94e
Update task.md
lgabrielvleon Oct 20, 2020
5226df4
Update solution.md
lgabrielvleon Oct 20, 2020
9c9b64f
Update task.md
lgabrielvleon Oct 20, 2020
ca42219
Update solution.md
lgabrielvleon Oct 20, 2020
466734d
Update task.md
lgabrielvleon Oct 20, 2020
9740728
Update solution.md
lgabrielvleon Oct 20, 2020
2e0bd7c
Update task.md
lgabrielvleon Oct 20, 2020
086ae04
Update index.html
lgabrielvleon Oct 20, 2020
db46b72
Update article.md
lgabrielvleon Oct 20, 2020
6439b88
Update article.md
lgabrielvleon Oct 21, 2020
2b32f2b
Update article.md
lgabrielvleon Oct 22, 2020
cf550f5
Update article.md
lgabrielvleon Oct 22, 2020
3763bb4
Update article.md
lgabrielvleon Oct 22, 2020
b5522eb
alineando
joaquinelio Oct 25, 2020
3a695f6
Update 2-ui/1-document/09-size-and-scroll/6-width-vs-clientwidth/task.md
lgabrielvleon Oct 26, 2020
ad78fbb
Update 2-ui/1-document/09-size-and-scroll/1-get-scroll-height-bottom/…
lgabrielvleon Oct 26, 2020
9821cfd
Update 2-ui/1-document/09-size-and-scroll/article.md
lgabrielvleon Oct 26, 2020
ea2eabf
Update 2-ui/1-document/09-size-and-scroll/article.md
lgabrielvleon Oct 26, 2020
1c91fcb
Update 2-ui/1-document/09-size-and-scroll/article.md
lgabrielvleon Oct 26, 2020
64e7ef4
Update 2-ui/1-document/09-size-and-scroll/article.md
lgabrielvleon Oct 26, 2020
5889c25
Update 2-ui/1-document/09-size-and-scroll/2-scrollbar-width/task.md
lgabrielvleon Oct 26, 2020
28eb465
Update 2-ui/1-document/09-size-and-scroll/2-scrollbar-width/task.md
lgabrielvleon Oct 26, 2020
989c60b
Update 2-ui/1-document/09-size-and-scroll/4-put-ball-in-center/soluti…
lgabrielvleon Oct 26, 2020
1e1a2bd
Update 2-ui/1-document/09-size-and-scroll/4-put-ball-in-center/soluti…
lgabrielvleon Oct 26, 2020
bb6abd8
Update 2-ui/1-document/09-size-and-scroll/4-put-ball-in-center/soluti…
lgabrielvleon Oct 26, 2020
4d76cf2
Update 2-ui/1-document/09-size-and-scroll/article.md
lgabrielvleon Oct 26, 2020
dd0e94f
Update 2-ui/1-document/09-size-and-scroll/2-scrollbar-width/task.md
lgabrielvleon Oct 26, 2020
3d6a862
Update 2-ui/1-document/09-size-and-scroll/4-put-ball-in-center/task.md
lgabrielvleon Oct 26, 2020
669d366
Update 2-ui/1-document/09-size-and-scroll/6-width-vs-clientwidth/solu…
lgabrielvleon Oct 26, 2020
b63c3a4
Update 2-ui/1-document/09-size-and-scroll/4-put-ball-in-center/task.md
lgabrielvleon Oct 26, 2020
0f2480e
Update 2-ui/1-document/09-size-and-scroll/6-width-vs-clientwidth/solu…
lgabrielvleon Oct 26, 2020
980057b
Update solution.md
lgabrielvleon Oct 26, 2020
f7ff985
Update 2-ui/1-document/09-size-and-scroll/2-scrollbar-width/solution.md
vplentinax Dec 17, 2020
ddb54ac
Update 2-ui/1-document/09-size-and-scroll/2-scrollbar-width/task.md
vplentinax Dec 17, 2020
00ed4fc
Update 2-ui/1-document/09-size-and-scroll/4-put-ball-in-center/task.md
vplentinax Dec 17, 2020
9d315d0
Update 2-ui/1-document/09-size-and-scroll/4-put-ball-in-center/task.md
vplentinax Dec 17, 2020
8012f83
Update 2-ui/1-document/09-size-and-scroll/6-width-vs-clientwidth/solu…
vplentinax Dec 17, 2020
62bca3f
Update 2-ui/1-document/09-size-and-scroll/6-width-vs-clientwidth/task.md
vplentinax Dec 17, 2020
cd7e165
Update 2-ui/1-document/09-size-and-scroll/article.md
vplentinax Dec 17, 2020
9970a93
Update 2-ui/1-document/09-size-and-scroll/article.md
vplentinax Dec 17, 2020
1344926
Update 2-ui/1-document/09-size-and-scroll/article.md
vplentinax Dec 17, 2020
29120e2
Update 2-ui/1-document/09-size-and-scroll/article.md
vplentinax Dec 17, 2020
25f7874
Update 2-ui/1-document/09-size-and-scroll/article.md
vplentinax Dec 17, 2020
601704f
Update 2-ui/1-document/09-size-and-scroll/article.md
vplentinax Dec 17, 2020
4e51234
Update 2-ui/1-document/09-size-and-scroll/article.md
vplentinax Dec 17, 2020
41d06ed
Update 2-ui/1-document/09-size-and-scroll/article.md
vplentinax Dec 17, 2020
d5be71f
Update 2-ui/1-document/09-size-and-scroll/article.md
vplentinax Dec 17, 2020
08f1899
Update 2-ui/1-document/09-size-and-scroll/article.md
vplentinax Dec 17, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
The solution is:
La solución es:

```js
let scrollBottom = elem.scrollHeight - elem.scrollTop - elem.clientHeight;
```

In other words: (full height) minus (scrolled out top part) minus (visible part) -- that's exactly the scrolled out bottom part.
En otras palabras: (altura total) menos (parte superior desplazada) menos (parte visible) -- esa es exactamente la parte inferior desplazada.
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
importance: 5
importancia: 5

---

# What's the scroll from the bottom?
# ¿Qué es el desplazamiento desde la parte inferior?

The `elem.scrollTop` property is the size of the scrolled out part from the top. How to get the size of the bottom scroll (let's call it `scrollBottom`)?
La propiedad `elem.scrollTop` es el tamaño desplazado desde la parte superior. ¿Cómo obtener el tamaño de la parte inferior desplazada (vamos a llamarlo `scrollBottom`)?

Write the code that works for an arbitrary `elem`.
Escribe el código que funcione para un `elem` arbitrario.

P.S. Please check your code: if there's no scroll or the element is fully scrolled down, then it should return `0`.
P.S. Por favor revisa tu código: si no hay desplazamiento o el elemento está complemamente desplazado, debería retornar `0`.
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
To get the scrollbar width, we can create an element with the scroll, but without borders and paddings.
Para obtener el ancho de la barra de desplazamiento, podemos crear un elemento con el scroll, pero sin bordes ni rellenos.

Then the difference between its full width `offsetWidth` and the inner content area width `clientWidth` will be exactly the scrollbar:
Entonces la diferencia entre su ancho completo `offsetWidth` y el ancho del area interior `clientWidth` será exactamente la barra de desplazamiento:

```js run
// create a div with the scroll
// crea a div con el scroll
let div = document.createElement('div');

div.style.overflowY = 'scroll';
div.style.width = '50px';
div.style.height = '50px';

// must put it in the document, otherwise sizes will be 0
// debe ponerlo en el documento, de lo contrario los tamaños serán 0
document.body.append(div);
let scrollWidth = div.offsetWidth - div.clientWidth;

Expand Down
10 changes: 5 additions & 5 deletions 2-ui/1-document/09-size-and-scroll/2-scrollbar-width/task.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
importance: 3
importancia: 3

---

# What is the scrollbar width?
# ¿Qué es el ancho de la barra de desplazamiento?

Write the code that returns the width of a standard scrollbar.
Escribe el código que retorna el tamaño de una barra de desplazamiento estandar.

For Windows it usually varies between `12px` and `20px`. If the browser doesn't reserve any space for it (the scrollbar is half-translucent over the text, also happens), then it may be `0px`.
Para Windows esto usualmente varía entre `12px` y `20px`. Si el navegador no reserva algun espacio para esto (la barra de desplazamiento es medio traslucido sobre el texto, también pasa), entonces puede ser `0px`.

P.S. The code should work for any HTML document, do not depend on its content.
P.S. El código debería funcionar con cualquier documento HTML, no depende de su contenido.
26 changes: 13 additions & 13 deletions 2-ui/1-document/09-size-and-scroll/4-put-ball-in-center/solution.md
Original file line number Diff line number Diff line change
@@ -1,53 +1,53 @@
The ball has `position:absolute`. It means that its `left/top` coordinates are measured from the nearest positioned element, that is `#field` (because it has `position:relative`).
La pelota tiene `position:absolute`. Significa que sus coordenadas `left/top` se miden desde el elemento posicionado más cercano, es decir `#field` (porque tiene `position:relative`).

The coordinates start from the inner left-upper corner of the field:
Las coordenadas incian desde el interior de la esquina superior izquierda del campo:

![](field.svg)

The inner field width/height is `clientWidth/clientHeight`. So the field center has coordinates `(clientWidth/2, clientHeight/2)`.
El interior del campo ancho/alto es `clientWidth/clientHeight`. Entonces el centro del campo tiene coordenadas `(clientWidth/2, clientHeight/2)`.

...But if we set `ball.style.left/top` to such values, then not the ball as a whole, but the left-upper edge of the ball would be in the center:
...Pero si configuramos `ball.style.left/top` a tales valores, entonces no la pelota en su conjunto, sino el borde superior izquierdo de la pelota estaría en el centro:

```js
ball.style.left = Math.round(field.clientWidth / 2) + 'px';
ball.style.top = Math.round(field.clientHeight / 2) + 'px';
```

Here's how it looks:
Así es como se ve:

[iframe height=180 src="ball-half"]

To align the ball center with the center of the field, we should move the ball to the half of its width to the left and to the half of its height to the top:
Para alinear la pelota al centro con el centro del campo, deberíamos mover la pelota a la mitad de su ancho a la izquierda y a la mitad de su altura hacia arriba:

```js
ball.style.left = Math.round(field.clientWidth / 2 - ball.offsetWidth / 2) + 'px';
ball.style.top = Math.round(field.clientHeight / 2 - ball.offsetHeight / 2) + 'px';
```

Now the ball is finally centered.
Ahora la pelota está finalmente centrada.

````warn header="Attention: the pitfall!"

The code won't work reliably while `<img>` has no width/height:
El codigo no funcionará seguramente mientras `<img>` no tenga width/height:

```html
<img src="ball.png" id="ball">
```
````

When the browser does not know the width/height of an image (from tag attributes or CSS), then it assumes them to equal `0` until the image finishes loading.
Cuando el navegador no conoce el ancho/alto de una imagen (de un atributo o CSS), entonces este asume que es igual a `0` hasta que la imagen termine de cargarse.

So the value of `ball.offsetWidth` will be `0` until the image loads. That leads to wrong coordinates in the code above.
Entonces el valor de `ball.offsetWidth` deberá ser `0` hasta que la imagen carge. Eso conduce a coordinadas incorrectas en el código anterior.

After the first load, the browser usually caches the image, and on reloads it will have the size immediately. But on the first load the value of `ball.offsetWidth` is `0`.
Después de la primera carga, el navegador usualmente almacena en caché la imagen, y cuando se vuelva a cargar esta tendrá el tamaño inmediatamente. Pero en la primera carga el valor de `ball.offsetWidth` es `0`.

We should fix that by adding `width/height` to `<img>`:
Deberíamos arreglar eso agregando `width/height` en `<img>`:

```html
<img src="ball.png" *!*width="40" height="40"*/!* id="ball">
```

...Or provide the size in CSS:
...O indicar el tamaño en CSS:

```css
#ball {
Expand Down
16 changes: 8 additions & 8 deletions 2-ui/1-document/09-size-and-scroll/4-put-ball-in-center/task.md
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
importance: 5
importancia: 5

---

# Place the ball in the field center
# Coloca la pelota en el centro del campo.

Here's how the source document looks:
Así es como se ve el documento de origen:

[iframe src="source" edit link height=180]

What are coordinates of the field center?
¿Cuales son las coordenadas del centro de campo?

Calculate them and use to place the ball into the center of the green field:
Calcúlelos y usalos para colocar la pelota en el centro del campo verde:

[iframe src="solution" height=180]

- The element should be moved by JavaScript, not CSS.
- The code should work with any ball size (`10`, `20`, `30` pixels) and any field size, not be bound to the given values.
- El elemento debe ser movido por JavaScript, no por CSS.
- El código debería funcionar con cualquier una pelota de cualquier tamaño (`10`, `20`, `30` pixels) y cualquier tamaño de campo, no debe estar vinculado a los valores dados.

P.S. Sure, centering could be done with CSS, but here we want exactly JavaScript. Further we'll meet other topics and more complex situations when JavaScript must be used. Here we do a "warm-up".
P.S. Claro, el centrado se podría hacer con CSS, pero aqui queremos exactamente con JavaScript. Además, conoceremos otros temas y situaciones más complejas en las que se debe utilizar JavaScript. Aquí hacemos un "calentamiento".
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
Differences:
Diferencias:

1. `clientWidth` is numeric, while `getComputedStyle(elem).width` returns a string with `px` at the end.
2. `getComputedStyle` may return non-numeric width like `"auto"` for an inline element.
3. `clientWidth` is the inner content area of the element plus paddings, while CSS width (with standard `box-sizing`) is the inner content area *without paddings*.
4. If there's a scrollbar and the browser reserves the space for it, some browser substract that space from CSS width (cause it's not available for content any more), and some do not. The `clientWidth` property is always the same: scrollbar size is substracted if reserved.
1. `clientWidth` es numérico, mientras `getComputedStyle(elem).width` retorna una cadena con `px` en el final.
2. `getComputedStyle` puede devolver un ancho no numérico como `"auto"` para un elemento en linea.
3. `clientWidth` es el contenido interior del area del elemento más los rellenos, mientras el ancho de CSS (con el estandar `box-sizing`) es el contenido interior del area *sin rellenos*.
4. Si hay una barra de desplazamiento y el navegador reserva espacio para esta, algunos navegadores restan ese espacio del ancho de CSS (por que no está disponibre para el contenido), y otros no. La propiedad `clientWidth` es siempre la misma: el tamaño de la barra de desplazamiento se resta si está reservado.
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
importance: 5
importancia: 5

---

# The difference: CSS width versus clientWidth
# La diferencia: CSS width versus clientWidth

What's the difference between `getComputedStyle(elem).width` and `elem.clientWidth`?
¿Cuál es la diferencia entre `getComputedStyle(elem).width` y `elem.clientWidth`?

Give at least 3 differences. The more the better.
Dar almenos 3 diferencias. Mientras más, mejor.
Loading