Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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:
A solução é:

```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.
Em outras palavras: (altura total) menos (parte rolada para fora no topo) menos (parte visível) -- isso é exatamente a parte rolada para fora na parte de baixo.
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ importance: 5

---

# What's the scroll from the bottom?
# Qual é a rolagem a partir de baixo?

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`)?
A propriedade `elem.scrollTop` é o tamanho da parte rolada para fora a partir do topo. Como obter o tamanho da rolagem a partir de baixo (vamos chamá-lo de `scrollBottom`)?

Write the code that works for an arbitrary `elem`.
Escreva o código que funcione para um `elem` arbitrário.

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. Teste seu código: se não houver rolagem ou o elemento estiver totalmente rolado para baixo, então ele deve 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 obter a largura da barra de rolagem, podemos criar um elemento com rolagem, mas sem bordas e preenchimentos.

Then the difference between its full width `offsetWidth` and the inner content area width `clientWidth` will be exactly the scrollbar:
Então a diferença entre sua largura total `offsetWidth` e a largura da área de conteúdo interna `clientWidth` será exatamente a barra de rolagem:

```js run
// create a div with the scroll
// cria um div com rolagem
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
// precisa colocá-lo no documento, senão os tamanhos serão 0
document.body.append(div);
let scrollWidth = div.offsetWidth - div.clientWidth;

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

---

# What is the scrollbar width?
# Qual é a largura da barra de rolagem?

Write the code that returns the width of a standard scrollbar.
Escreva o código que retorna a largura de uma barra de rolagem padrão.

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`.
No Windows, geralmente varia entre `12px` e `20px`. Se o navegador não reservar nenhum espaço para ela (a barra de rolagem fica semitransparente sobre o texto, isso também acontece), então pode ser `0px`.

P.S. The code should work for any HTML document, do not depend on its content.
P.S. O código deve funcionar para qualquer documento HTML, sem depender do seu conteúdo.
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@
let ball = document.getElementById('ball')
let field = document.getElementById('field')

// ball.offsetWidth=0 before image loaded!
// to fix: set width
// ball.offsetWidth=0 antes da imagem carregar!
// para corrigir: defina o width
ball.style.left = Math.round(field.clientWidth / 2) + 'px'
ball.style.top = Math.round(field.clientHeight / 2) + 'px'
</script>
Expand Down
28 changes: 14 additions & 14 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`).
A bola tem `position:absolute`. Isso significa que suas coordenadas `left/top` são medidas a partir do elemento posicionado mais próximo, que é `#field` (porque ele tem `position:relative`).

The coordinates start from the inner left-upper corner of the field:
As coordenadas começam a partir do canto interno superior-esquerdo do campo:

![](field.svg)

The inner field width/height is `clientWidth/clientHeight`. So the field center has coordinates `(clientWidth/2, clientHeight/2)`.
A largura/altura interna do campo é `clientWidth/clientHeight`. Então o centro do campo tem 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:
...Mas se definirmos `ball.style.left/top` com esses valores, então não será a bola como um todo, mas o canto superior-esquerdo da bola que ficará no 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:
Veja como fica:

[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 alinhar o centro da bola com o centro do campo, devemos mover a bola em metade da sua largura para a esquerda e em metade da sua altura para cima:

```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.
Agora a bola está finalmente centralizada.

````warn header="Attention: the pitfall!"
````warn header="Atenção: a armadilha!"

The code won't work reliably while `<img>` has no width/height:
O código não vai funcionar de forma confiável enquanto a `<img>` não tiver 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.
Quando o navegador não sabe a largura/altura de uma imagem (a partir de atributos da tag ou do CSS), ele assume que elas são iguais a `0` até que a imagem termine de carregar.

So the value of `ball.offsetWidth` will be `0` until the image loads. That leads to wrong coordinates in the code above.
Então o valor de `ball.offsetWidth` será `0` até a imagem carregar. Isso leva a coordenadas erradas no código acima.

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`.
Depois do primeiro carregamento, o navegador geralmente armazena a imagem em cache, e nos recarregamentos ela terá o tamanho imediatamente. Mas no primeiro carregamento o valor de `ball.offsetWidth` é `0`.

We should fix that by adding `width/height` to `<img>`:
Devemos corrigir isso adicionando `width/height` à `<img>`:

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

...Or provide the size in CSS:
...Ou fornecer o tamanho no CSS:

```css
#ball {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@


<script>
// ball.offsetWidth=0 before image loaded!
// to fix: set width
// ball.offsetWidth=0 antes da imagem carregar!
// para corrigir: defina o width
ball.style.left = Math.round(field.clientWidth / 2 - ball.offsetWidth / 2) + 'px'
ball.style.top = Math.round(field.clientHeight / 2 - ball.offsetHeight / 2) + 'px'
</script>
Expand Down
14 changes: 7 additions & 7 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
Expand Up @@ -2,19 +2,19 @@ importance: 5

---

# Place the ball in the field center
# Coloque a bola no centro do campo

Here's how the source document looks:
Veja como fica o documento original:

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

What are coordinates of the field center?
Quais são as coordenadas do centro do campo?

Calculate them and use to place the ball into the center of the green field:
Calcule-as e use-as para colocar a bola no centro do 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.
- O elemento deve ser movido por JavaScript, não por CSS.
- O código deve funcionar com qualquer tamanho de bola (`10`, `20`, `30` pixels) e qualquer tamanho de campo, sem ficar amarrado aos 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, a centralização poderia ser feita com CSS, mas aqui queremos exatamente JavaScript. Mais adiante vamos encontrar outros tópicos e situações mais complexas em que o JavaScript precisa ser usado. Aqui fazemos um "aquecimento".
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
Differences:
Diferenças:

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` é numérico, enquanto `getComputedStyle(elem).width` retorna uma string com `px` no final.
2. `getComputedStyle` pode retornar uma largura não numérica, como `"auto"`, para um elemento inline.
3. `clientWidth` é a área de conteúdo interna do elemento mais os preenchimentos, enquanto a largura CSS (com o `box-sizing` padrão) é a área de conteúdo interna *sem os preenchimentos*.
4. Se houver uma barra de rolagem e o navegador reservar espaço para ela, alguns navegadores subtraem esse espaço da largura CSS (já que ele não está mais disponível para o conteúdo), e alguns não subtraem. A propriedade `clientWidth` é sempre a mesma: o tamanho da barra de rolagem é subtraído se ela estiver reservada.
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ importance: 5

---

# The difference: CSS width versus clientWidth
# A diferença: width do CSS versus clientWidth

What's the difference between `getComputedStyle(elem).width` and `elem.clientWidth`?
Qual é a diferença entre `getComputedStyle(elem).width` e `elem.clientWidth`?

Give at least 3 differences. The more the better.
Dê pelo menos 3 diferenças. Quanto mais, melhor.
Loading