Skip to content
Merged
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
Expand Up @@ -7,13 +7,13 @@

<body>

<input type="button" id="hider" value="Click to hide the text" />
<input type="button" id="hider" value="Clique para ocultar o texto" />

<div id="text">Text</div>
<div id="text">Texto</div>

<script>
// Here it doesn't matter how we hide the text,
// could also use style.display:
// Aqui não importa como ocultamos o texto,
// também poderíamos usar style.display:
document.getElementById('hider').onclick = function() {
document.getElementById('text').hidden = true;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@

<body>

<input type="button" id="hider" value="Click to hide the text" />
<input type="button" id="hider" value="Clique para ocultar o texto" />

<div id="text">Text</div>
<div id="text">Texto</div>

<script>
/* your code */
/* seu código */
</script>

</body>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ importance: 5

---

# Hide on click
# Ocultar ao clicar

Add JavaScript to the `button` to make `<div id="text">` disappear when we click it.
Adicione JavaScript ao `button` para fazer `<div id="text">` desaparecer quando clicarmos nele.

The demo:
A demo:

[iframe border=1 src="solution" height=80]
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
Can use `this` in the handler to reference "the element itself" here:
Podemos usar `this` no manipulador para referenciar "o próprio elemento" aqui:

```html run height=50
<input type="button" onclick="this.hidden=true" value="Click to hide">
<input type="button" onclick="this.hidden=true" value="Clique para ocultar">
```
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ importance: 5

---

# Hide self
# Oculte a si mesmo

Create a button that hides itself on click.
Crie um botão que se oculte ao ser clicado.

```online
Like this:
<input type="button" onclick="this.hidden=true" value="Click to hide">
Assim:
<input type="button" onclick="this.hidden=true" value="Clique para ocultar">
```
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
The answer: `1` and `2`.
A resposta: `1` e `2`.

The first handler triggers, because it's not removed by `removeEventListener`. To remove the handler we need to pass exactly the function that was assigned. And in the code a new function is passed, that looks the same, but is still another function.
O primeiro manipulador é acionado, porque não é removido por `removeEventListener`. Para remover o manipulador precisamos passar exatamente a função que foi atribuída. E no código uma nova função é passada, que parece a mesma, mas ainda é outra função.

To remove a function object, we need to store a reference to it, like this:
Para remover um objeto de função, precisamos armazenar uma referência a ele, assim:

```js
function handler() {
Expand All @@ -13,4 +13,4 @@ button.addEventListener("click", handler);
button.removeEventListener("click", handler);
```

The handler `button.onclick` works independently and in addition to `addEventListener`.
O manipulador `button.onclick` funciona independentemente, além do `addEventListener`.
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ importance: 5

---

# Which handlers run?
# Quais manipuladores são executados?

There's a button in the variable. There are no handlers on it.
Há um botão na variável. Não há manipuladores nele.

Which handlers run on click after the following code? Which alerts show up?
Quais manipuladores são executados no clique depois do código a seguir? Quais alertas aparecem?

```js no-beautify
button.addEventListener("click", () => alert("1"));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@

First we need to choose a method of positioning the ball.
Primeiro precisamos escolher um método de posicionamento da bola.

We can't use `position:fixed` for it, because scrolling the page would move the ball from the field.
Não podemos usar `position:fixed` para ela, porque rolar a página moveria a bola para fora do campo.

So we should use `position:absolute` and, to make the positioning really solid, make `field` itself positioned.
Então devemos usar `position:absolute` e, para tornar o posicionamento realmente sólido, tornar o próprio `field` posicionado.

Then the ball will be positioned relatively to the field:
Então a bola será posicionada em relação ao campo:

```css
#field {
Expand All @@ -16,36 +16,36 @@ Then the ball will be positioned relatively to the field:

#ball {
position: absolute;
left: 0; /* relative to the closest positioned ancestor (field) */
left: 0; /* relativo ao ancestral posicionado mais próximo (field) */
top: 0;
transition: 1s all; /* CSS animation for left/top makes the ball fly */
transition: 1s all; /* animação CSS para left/top faz a bola "voar" */
}
```

Next we need to assign the correct `ball.style.left/top`. They contain field-relative coordinates now.
Agora precisamos atribuir o `ball.style.left/top` correto. Eles agora contêm coordenadas relativas ao campo.

Here's the picture:
Aqui está a imagem:

![](move-ball-coords.svg)

We have `event.clientX/clientY` -- window-relative coordinates of the click.
Temos `event.clientX/clientY` -- coordenadas do clique relativas à janela.

To get field-relative `left` coordinate of the click, we can substract the field left edge and the border width:
Para obter a coordenada `left` do clique relativa ao campo, podemos subtrair a borda esquerda do campo e a largura da borda:

```js
let left = event.clientX - fieldCoords.left - field.clientLeft;
```

Normally, `ball.style.left` means the "left edge of the element" (the ball). So if we assign that `left`, then the ball edge, not center, would be under the mouse cursor.
Normalmente, `ball.style.left` significa "a borda esquerda do elemento" (a bola). Então, se atribuirmos esse `left`, a borda da bola, não o centro, ficaria sob o cursor do mouse.

We need to move the ball half-width left and half-height up to make it center.
Precisamos mover a bola metade da largura para a esquerda e metade da altura para cima, para centralizá-la.

So the final `left` would be:
Então o `left` final seria:

```js
let left = event.clientX - fieldCoords.left - field.clientLeft - ball.offsetWidth/2;
```

The vertical coordinate is calculated using the same logic.
A coordenada vertical é calculada usando a mesma lógica.

Please note that the ball width/height must be known at the time we access `ball.offsetWidth`. Should be specified in HTML or CSS.
Note que a largura/altura da bola deve ser conhecida no momento em que acessamos `ball.offsetWidth`. Deve ser especificada em HTML ou CSS.
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@

<body style="height:2000px">

Click on a field to move the ball there.
Clique em um campo para mover a bola para lá.
<br>


Expand All @@ -39,29 +39,29 @@
<script>
field.onclick = function(event) {

// window-relative field coordinates
// coordenadas do campo relativas à janela
let fieldCoords = this.getBoundingClientRect();

// the ball has position:absolute, the field: position:relative
// so ball coordinates are relative to the field inner left-upper corner
// a bola tem position:absolute, o campo: position:relative
// então as coordenadas da bola são relativas ao canto interno superior-esquerdo do campo
let ballCoords = {
top: event.clientY - fieldCoords.top - field.clientTop - ball.clientHeight / 2,
left: event.clientX - fieldCoords.left - field.clientLeft - ball.clientWidth / 2
};

// prevent crossing the top field boundary
// impede cruzar o limite superior do campo
if (ballCoords.top < 0) ballCoords.top = 0;

// prevent crossing the left field boundary
// impede cruzar o limite esquerdo do campo
if (ballCoords.left < 0) ballCoords.left = 0;


// // prevent crossing the right field boundary
// // impede cruzar o limite direito do campo
if (ballCoords.left + ball.clientWidth > field.clientWidth) {
ballCoords.left = field.clientWidth - ball.clientWidth;
}

// prevent crossing the bottom field boundary
// impede cruzar o limite inferior do campo
if (ballCoords.top + ball.clientHeight > field.clientHeight) {
ballCoords.top = field.clientHeight - ball.clientHeight;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@

<body style="height:2000px">

Click on a field to move the ball there.
<br> The ball should never leave the field.
Clique em um campo para mover a bola para lá.
<br> A bola nunca deve deixar o campo.


<div id="field">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,20 @@ importance: 5

---

# Move the ball across the field
# Mova a bola pelo campo

Move the ball across the field to a click. Like this:
Mova a bola pelo campo ao clicar. Assim:

[iframe src="solution" height="260" link]

Requirements:
Requisitos:

- The ball center should come exactly under the pointer on click (if possible without crossing the field edge).
- CSS-animation is welcome.
- The ball must not cross field boundaries.
- When the page is scrolled, nothing should break.
- O centro da bola deve ficar exatamente sob o ponteiro ao clicar (se possível, sem cruzar a borda do campo).
- Animação CSS é bem-vinda.
- A bola não deve cruzar os limites do campo.
- Quando a página é rolada, nada deve quebrar.

Notes:
Notas:

- The code should also work with different ball and field sizes, not be bound to any fixed values.
- Use properties `event.clientX/event.clientY` for click coordinates.
- O código também deve funcionar com tamanhos diferentes de bola e campo, sem ficar amarrado a nenhum valor fixo.
- Use as propriedades `event.clientX/event.clientY` para as coordenadas do clique.
Original file line number Diff line number Diff line change
@@ -1,47 +1,47 @@

# HTML/CSS
First let's create HTML/CSS.
Primeiro vamos criar o HTML/CSS.

A menu is a standalone graphical component on the page, so it's better to put it into a single DOM element.
Um menu é um componente gráfico independente na página, então é melhor colocá-lo em um único elemento do DOM.

A list of menu items can be laid out as a list `ul/li`.
Uma lista de itens do menu pode ser organizada como uma lista `ul/li`.

Here's the example structure:
Aqui está a estrutura de exemplo:

```html
<div class="menu">
<span class="title">Sweeties (click me)!</span>
<span class="title">Doces (clique em mim)!</span>
<ul>
<li>Cake</li>
<li>Donut</li>
<li>Honey</li>
<li>Bolo</li>
<li>Rosquinha</li>
<li>Mel</li>
</ul>
</div>
```

We use `<span>` for the title, because `<div>` has an implicit `display:block` on it, and it will occupy 100% of the horizontal width.
Usamos `<span>` para o título, porque `<div>` tem um `display:block` implícito, e vai ocupar 100% da largura horizontal.

Like this:
Assim:

```html autorun height=50
<div style="border: solid red 1px" onclick="alert(1)">Sweeties (click me)!</div>
<div style="border: solid red 1px" onclick="alert(1)">Doces (clique em mim)!</div>
```

So if we set `onclick` on it, then it will catch clicks to the right of the text.
Então, se definirmos `onclick` nele, ele vai capturar cliques à direita do texto.

As `<span>` has an implicit `display: inline`, it occupies exactly enough place to fit all the text:
Como `<span>` tem um `display: inline` implícito, ele ocupa exatamente o espaço suficiente para caber todo o texto:

```html autorun height=50
<span style="border: solid red 1px" onclick="alert(1)">Sweeties (click me)!</span>
<span style="border: solid red 1px" onclick="alert(1)">Doces (clique em mim)!</span>
```

# Toggling the menu
# Alternando o menu

Toggling the menu should change the arrow and show/hide the menu list.
Alternar o menu deve mudar a seta e mostrar/ocultar a lista do menu.

All these changes are perfectly handled by CSS. In JavaScript we should label the current state of the menu by adding/removing the class `.open`.
Todas essas mudanças são perfeitamente tratadas pelo CSS. Em JavaScript devemos sinalizar o estado atual do menu adicionando/removendo a classe `.open`.

Without it, the menu will be closed:
Sem ela, o menu ficará fechado:

```css
.menu ul {
Expand All @@ -58,7 +58,7 @@ Without it, the menu will be closed:
}
```

...And with `.open` the arrow changes and the list shows up:
...E com `.open` a seta muda e a lista aparece:

```css
.menu.open .title::before {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,11 @@
<body>

<div id="sweeties" class="menu">
<span class="title">Sweeties (click me)!</span>
<span class="title">Doces (clique em mim)!</span>
<ul>
<li>Cake</li>
<li>Donut</li>
<li>Honey</li>
<li>Bolo</li>
<li>Rosquinha</li>
<li>Mel</li>
</ul>

</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@
</head>
<body>

▶ ▼ Sweeties (click me)!
▶ ▼ Doces (clique em mim)!
<ul>
<li>Cake</li>
<li>Donut</li>
<li>Honey</li>
<li>Bolo</li>
<li>Rosquinha</li>
<li>Mel</li>
</ul>

</body>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ importance: 5

---

# Create a sliding menu
# Crie um menu deslizante

Create a menu that opens/collapses on click:
Crie um menu que abre/recolhe ao clicar:

[iframe border=1 height=100 src="solution"]

P.S. HTML/CSS of the source document is to be modified.
P.S. O HTML/CSS do documento fonte deve ser modificado.
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@

To add the button we can use either `position:absolute` (and make the pane `position:relative`) or `float:right`. The `float:right` has the benefit that the button never overlaps the text, but `position:absolute` gives more freedom. So the choice is yours.
Para adicionar o botão podemos usar `position:absolute` (e tornar o painel `position:relative`) ou `float:right`. O `float:right` tem a vantagem de o botão nunca sobrepor o texto, mas `position:absolute` dá mais liberdade. Então a escolha é sua.

Then for each pane the code can be like:
Então, para cada painel, o código pode ser assim:
```js
pane.insertAdjacentHTML("afterbegin", '<button class="remove-button">[x]</button>');
```

Then the `<button>` becomes `pane.firstChild`, so we can add a handler to it like this:
Então o `<button>` se torna `pane.firstChild`, então podemos adicionar um manipulador a ele assim:

```js
pane.firstChild.onclick = () => pane.remove();
Expand Down
Loading