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
@@ -1,8 +1,8 @@
Answer: **1 and 3**.
Resposta: **1 e 3**.

Both commands result in adding the `text` "as text" into the `elem`.
Ambos os comandos resultam em adicionar o `text` "como texto" dentro de `elem`.

Here's an example:
Aqui está um exemplo:

```html run height=80
<div id="elem1"></div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ importance: 5

# createTextNode vs innerHTML vs textContent

We have an empty DOM element `elem` and a string `text`.
Temos um elemento do DOM vazio `elem` e uma string `text`.

Which of these 3 commands will do exactly the same?
Qual destes 3 comandos vai fazer exatamente a mesma coisa?

1. `elem.append(document.createTextNode(text))`
2. `elem.innerHTML = text`
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
First, let's make HTML/CSS.
Primeiro, vamos fazer o HTML/CSS.

Each component of the time would look great in its own `<span>`:
Cada componente da hora ficaria ótimo em seu próprio `<span>`:

```html
<div id="clock">
<span class="hour">hh</span>:<span class="min">mm</span>:<span class="sec">ss</span>
</div>
```

Also we'll need CSS to color them.
Também vamos precisar de CSS para colori-los.

The `update` function will refresh the clock, to be called by `setInterval` every second:
A função `update` vai atualizar o relógio, sendo chamada pelo `setInterval` a cada segundo:

```js
function update() {
Expand All @@ -32,15 +32,15 @@ function update() {
}
```

In the line `(*)` we every time check the current date. The calls to `setInterval` are not reliable: they may happen with delays.
Na linha `(*)` verificamos a data atual a cada vez. As chamadas a `setInterval` não são confiáveis: podem acontecer com atrasos.

The clock-managing functions:
As funções que gerenciam o relógio:

```js
let timerId;

function clockStart() { // run the clock
if (!timerId) { // only set a new interval if the clock is not running
function clockStart() { // inicia o relógio
if (!timerId) { // só define um novo intervalo se o relógio não estiver em execução
timerId = setInterval(update, 1000);
}
update(); // (*)
Expand All @@ -52,6 +52,6 @@ function clockStop() {
}
```

Please note that the call to `update()` is not only scheduled in `clockStart()`, but immediately run in the line `(*)`. Otherwise the visitor would have to wait till the first execution of `setInterval`. And the clock would be empty till then.
Note que a chamada a `update()` não é apenas agendada em `clockStart()`, mas também executada imediatamente na linha `(*)`. Caso contrário, o visitante teria que esperar até a primeira execução do `setInterval`. E o relógio ficaria vazio até então.

Also it is important to set a new interval in `clockStart()` only when the clock is not running. Otherways clicking the start button several times would set multiple concurrent intervals. Even worse - we would only keep the `timerID` of the last interval, losing references to all others. Then we wouldn't be able to stop the clock ever again! Note that we need to clear the `timerID` when the clock is stopped in the line `(**)`, so that it can be started again by running `clockStart()`.
Também é importante definir um novo intervalo em `clockStart()` apenas quando o relógio não estiver em execução. Caso contrário, clicar no botão de início várias vezes definiria múltiplos intervalos simultâneos. Pior ainda - manteríamos apenas o `timerId` do último intervalo, perdendo as referências a todos os outros. Então nunca mais conseguiríamos parar o relógio! Note que precisamos limpar o `timerId` quando o relógio é parado na linha `(**)`, para que ele possa ser iniciado novamente ao executar `clockStart()`.
Original file line number Diff line number Diff line change
Expand Up @@ -43,26 +43,26 @@
}

function clockStart() {
// set a new interval only if the clock is stopped
// otherwise we would rewrite the timerID reference to the running interval and wouldn't be able to stop the clock ever again
// define um novo intervalo apenas se o relógio estiver parado
// caso contrário, reescreveríamos a referência timerId do intervalo em execução e nunca mais conseguiríamos parar o relógio
if (!timerId) {
timerId = setInterval(update, 1000);
}
update(); // <-- start right now, don't wait 1 second till the first setInterval works
update(); // <-- começa agora mesmo, não espera 1 segundo até o primeiro setInterval funcionar
}

function clockStop() {
clearInterval(timerId);
timerId = null; // <-- clear timerID to indicate that the clock has been stopped, so that it is possible to start it again in clockStart()
timerId = null; // <-- limpa o timerId para indicar que o relógio foi parado, para que seja possível iniciá-lo novamente em clockStart()
}

</script>

<!-- click on this button calls clockStart() -->
<input type="button" onclick="clockStart()" value="Start">
<!-- clicar neste botão chama clockStart() -->
<input type="button" onclick="clockStart()" value="Começar">

<!-- click on this button calls clockStop() -->
<input type="button" onclick="clockStop()" value="Stop">
<!-- clicar neste botão chama clockStop() -->
<input type="button" onclick="clockStop()" value="Parar">

</body>
</html>
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
<html>
<body>

<!-- click on this button calls clockStart() -->
<input type="button" onclick="clockStart()" value="Start">
<!-- clicar neste botão chama clockStart() -->
<input type="button" onclick="clockStart()" value="Começar">

<!-- click on this button calls clockStop() -->
<input type="button" onclick="clockStop()" value="Stop">
<!-- clicar neste botão chama clockStop() -->
<input type="button" onclick="clockStop()" value="Parar">

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

---

# Colored clock with setInterval
# Relógio colorido com setInterval

Create a colored clock like here:
Crie um relógio colorido como este:

[iframe src="solution" height=60]

Use HTML/CSS for the styling, JavaScript only updates time in elements.
Use HTML/CSS para a estilização, o JavaScript só atualiza a hora nos elementos.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

When we need to insert a piece of HTML somewhere, `insertAdjacentHTML` is the best fit.
Quando precisamos inserir um pedaço de HTML em algum lugar, `insertAdjacentHTML` é a melhor opção.

The solution:
A solução:

```js
one.insertAdjacentHTML('afterend', '<li>2</li><li>3</li>');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ importance: 5

---

# Insert the HTML in the list
# Insira o HTML na lista

Write the code to insert `<li>2</li><li>3</li>` between two `<li>` here:
Escreva o código para inserir `<li>2</li><li>3</li>` entre dois `<li>` aqui:

```html
<ul id="ul">
Expand Down
14 changes: 7 additions & 7 deletions 2-ui/1-document/07-modifying-document/12-sort-table/solution.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
The solution is short, yet may look a bit tricky, so here I provide it with extensive comments:
A solução é curta, mas pode parecer um pouco complicada, então aqui eu a apresento com comentários extensos:

```js
let sortedRows = Array.from(table.tBodies[0].rows) // 1
Expand All @@ -7,12 +7,12 @@ let sortedRows = Array.from(table.tBodies[0].rows) // 1
table.tBodies[0].append(...sortedRows); // (3)
```

The step-by-step algorthm:
O algoritmo passo a passo:

1. Get all `<tr>`, from `<tbody>`.
2. Then sort them comparing by the content of the first `<td>` (the name field).
3. Now insert nodes in the right order by `.append(...sortedRows)`.
1. Obtenha todos os `<tr>`, de dentro do `<tbody>`.
2. Depois ordene-os comparando pelo conteúdo do primeiro `<td>` (o campo do nome).
3. Agora insira os nós na ordem correta com `.append(...sortedRows)`.

We don't have to remove row elements, just "re-insert", they leave the old place automatically.
Não precisamos remover os elementos de linha, apenas "reinseri-los", eles saem do lugar antigo automaticamente.

P.S. In our case, there's an explicit `<tbody>` in the table, but even if HTML table doesn't have `<tbody>`, the DOM structure always has it.
P.S. No nosso caso, há um `<tbody>` explícito na tabela, mas mesmo que a tabela HTML não tenha `<tbody>`, a estrutura do DOM sempre o terá.
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<table id="table">
<thead>
<tr>
<th>Name</th><th>Surname</th><th>Age</th>
<th>Nome</th><th>Sobrenome</th><th>Idade</th>
</tr>
</thead>
<tbody>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<table id="table">
<thead>
<tr>
<th>Name</th><th>Surname</th><th>Age</th>
<th>Nome</th><th>Sobrenome</th><th>Idade</th>
</tr>
</thead>
<tbody>
Expand All @@ -23,5 +23,5 @@
</table>

<script>
// ... your code ...
// ... seu código ...
</script>
10 changes: 5 additions & 5 deletions 2-ui/1-document/07-modifying-document/12-sort-table/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ importance: 5

---

# Sort the table
# Ordene a tabela

There's a table:
Há uma tabela:

```html run
<table>
<thead>
<tr>
<th>Name</th><th>Surname</th><th>Age</th>
<th>Nome</th><th>Sobrenome</th><th>Idade</th>
</tr>
</thead>
<tbody>
Expand All @@ -30,6 +30,6 @@ There's a table:
</table>
```

There may be more rows in it.
Pode haver mais linhas nela.

Write the code to sort it by the `"name"` column.
Escreva o código para ordená-la pela coluna `"nome"`.
10 changes: 5 additions & 5 deletions 2-ui/1-document/07-modifying-document/4-clear-elem/solution.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@

First, let's see how *not* to do it:
Primeiro, vamos ver como *não* fazer isso:

```js
function clear(elem) {
Expand All @@ -9,11 +9,11 @@ function clear(elem) {
}
```

That won't work, because the call to `remove()` shifts the collection `elem.childNodes`, so elements start from the index `0` every time. But `i` increases, and some elements will be skipped.
Isso não vai funcionar, porque a chamada a `remove()` desloca a coleção `elem.childNodes`, então os elementos começam a partir do índice `0` a cada vez. Mas `i` aumenta, e alguns elementos serão pulados.

The `for..of` loop also does the same.
O loop `for..of` também faz a mesma coisa.

The right variant could be:
A variante correta poderia ser:

```js
function clear(elem) {
Expand All @@ -23,7 +23,7 @@ function clear(elem) {
}
```

And also there's a simpler way to do the same:
E também há um jeito mais simples de fazer a mesma coisa:

```js
function clear(elem) {
Expand Down
12 changes: 6 additions & 6 deletions 2-ui/1-document/07-modifying-document/4-clear-elem/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,19 @@ importance: 5

---

# Clear the element
# Limpe o elemento

Create a function `clear(elem)` that removes everything from the element.
Crie uma função `clear(elem)` que remove tudo do elemento.

```html run height=60
<ol id="elem">
<li>Hello</li>
<li>World</li>
<li>Olá</li>
<li>Mundo</li>
</ol>

<script>
function clear(elem) { /* your code */ }
function clear(elem) { /* seu código */ }

clear(elem); // clears the list
clear(elem); // limpa a lista
</script>
```
10 changes: 5 additions & 5 deletions 2-ui/1-document/07-modifying-document/5-why-aaa/solution.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
The HTML in the task is incorrect. That's the reason of the odd thing.
O HTML na tarefa está incorreto. Essa é a razão da coisa estranha.

The browser has to fix it automatically. But there may be no text inside the `<table>`: according to the spec only table-specific tags are allowed. So the browser shows `"aaa"` *before* the `<table>`.
O navegador precisa corrigi-lo automaticamente. Mas não pode haver texto dentro de `<table>`: de acordo com a especificação, só são permitidas tags específicas de tabela. Então o navegador mostra `"aaa"` *antes* da `<table>`.

Now it's obvious that when we remove the table, it remains.
Agora é óbvio que, quando removemos a tabela, ele permanece.

The question can be easily answered by exploring the DOM using the browser tools. You'll see `"aaa"` before the `<table>`.
A pergunta pode ser facilmente respondida explorando o DOM usando as ferramentas do navegador. Você vai ver `"aaa"` antes da `<table>`.

The HTML standard specifies in detail how to process bad HTML, and such behavior of the browser is correct.
O padrão HTML especifica em detalhes como processar HTML incorreto, e esse comportamento do navegador está correto.
14 changes: 7 additions & 7 deletions 2-ui/1-document/07-modifying-document/5-why-aaa/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,26 @@ importance: 1

---

# Why does "aaa" remain?
# Por que "aaa" permanece?

In the example below, the call `table.remove()` removes the table from the document.
No exemplo abaixo, a chamada `table.remove()` remove a tabela do documento.

But if you run it, you can see that the text `"aaa"` is still visible.
Mas se você executar, pode ver que o texto `"aaa"` ainda fica visível.

Why does that happen?
Por que isso acontece?

```html height=100 run
<table id="table">
aaa
<tr>
<td>Test</td>
<td>Teste</td>
</tr>
</table>

<script>
alert(table); // the table, as it should be
alert(table); // a tabela, como deveria ser

table.remove();
// why there's still "aaa" in the document?
// por que ainda há "aaa" no documento?
</script>
```
Original file line number Diff line number Diff line change
@@ -1 +1 @@
Please note the usage of `textContent` to assign the `<li>` content.
Note o uso de `textContent` para atribuir o conteúdo do `<li>`.
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
<!DOCTYPE HTML>
<html>
<body>
<h1>Create a list</h1>
<h1>Crie uma lista</h1>

<script>
let ul = document.createElement('ul');
document.body.append(ul);

while (true) {
let data = prompt("Enter the text for the list item", "");
let data = prompt("Digite o texto do item da lista", "");

if (!data) {
break;
Expand Down
16 changes: 8 additions & 8 deletions 2-ui/1-document/07-modifying-document/6-create-list/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,18 @@ importance: 4

---

# Create a list
# Crie uma lista

Write an interface to create a list from user input.
Escreva uma interface para criar uma lista a partir da entrada do usuário.

For every list item:
Para cada item da lista:

1. Ask a user about its content using `prompt`.
2. Create the `<li>` with it and add it to `<ul>`.
3. Continue until the user cancels the input (by pressing `key:Esc` or via an empty entry).
1. Pergunte ao usuário sobre seu conteúdo usando `prompt`.
2. Crie o `<li>` com ele e adicione-o ao `<ul>`.
3. Continue até que o usuário cancele a entrada (pressionando `key:Esc` ou por meio de uma entrada vazia).

All elements should be created dynamically.
Todos os elementos devem ser criados dinamicamente.

If a user types HTML-tags, they should be treated like a text.
Se um usuário digitar tags HTML, elas devem ser tratadas como texto.

[demo src="solution"]
Loading