diff --git a/2-ui/2-events/04-default-browser-action/1-why-return-false-fails/solution.md b/2-ui/2-events/04-default-browser-action/1-why-return-false-fails/solution.md index 4d175ca01..af47238a5 100644 --- a/2-ui/2-events/04-default-browser-action/1-why-return-false-fails/solution.md +++ b/2-ui/2-events/04-default-browser-action/1-why-return-false-fails/solution.md @@ -1,16 +1,16 @@ -When the browser reads the `on*` attribute like `onclick`, it creates the handler from its content. +Quando o navegador lê o atributo `on*`, como `onclick`, ele cria o manipulador a partir do seu conteúdo. -For `onclick="handler()"` the function will be: +Para `onclick="handler()"` a função será: ```js function(event) { - handler() // the content of onclick + handler() // o conteúdo de onclick } ``` -Now we can see that the value returned by `handler()` is not used and does not affect the result. +Agora podemos ver que o valor retornado por `handler()` não é usado e não afeta o resultado. -The fix is simple: +A correção é simples: ```html run -the browser will go to w3.org +o navegador vai para w3.org ``` -The browser follows the URL on click, but we don't want it. +O navegador segue a URL ao clicar, mas não queremos isso. -How to fix? +Como corrigir? diff --git a/2-ui/2-events/04-default-browser-action/2-catch-link-navigation/solution.md b/2-ui/2-events/04-default-browser-action/2-catch-link-navigation/solution.md index 25079cb8d..a612d1123 100644 --- a/2-ui/2-events/04-default-browser-action/2-catch-link-navigation/solution.md +++ b/2-ui/2-events/04-default-browser-action/2-catch-link-navigation/solution.md @@ -1,5 +1,5 @@ -That's a great use of the event delegation pattern. +Esse é um ótimo uso do padrão de delegação de eventos. -In real life instead of asking we can send a "logging" request to the server that saves the information about where the visitor left. Or we can load the content and show it right in the page (if allowable). +Na vida real, em vez de perguntar, podemos enviar uma requisição de "log" ao servidor que salva a informação sobre por onde o visitante saiu. Ou podemos carregar o conteúdo e mostrá-lo diretamente na página (se permitido). -All we need is to catch the `contents.onclick` and use `confirm` to ask the user. A good idea would be to use `link.getAttribute('href')` instead of `link.href` for the URL. See the solution for details. +Tudo que precisamos é capturar `contents.onclick` e usar `confirm` para perguntar ao usuário. Uma boa ideia seria usar `link.getAttribute('href')` em vez de `link.href` para a URL. Veja a solução para os detalhes. diff --git a/2-ui/2-events/04-default-browser-action/2-catch-link-navigation/solution.view/index.html b/2-ui/2-events/04-default-browser-action/2-catch-link-navigation/solution.view/index.html index 51ac0838b..44dc7e92b 100644 --- a/2-ui/2-events/04-default-browser-action/2-catch-link-navigation/solution.view/index.html +++ b/2-ui/2-events/04-default-browser-action/2-catch-link-navigation/solution.view/index.html @@ -16,7 +16,7 @@
#contents

- How about to read Wikipedia or visit W3.org and learn about modern standards? + Que tal ler a Wikipedia ou visitar W3.org e aprender sobre os padrões modernos?

@@ -24,7 +24,7 @@ contents.onclick = function(event) { function handleLink(href) { - let isLeaving = confirm(`Leave for ${href}?`); + let isLeaving = confirm(`Sair para ${href}?`); if (!isLeaving) return false; } @@ -35,6 +35,6 @@ } }; - + diff --git a/2-ui/2-events/04-default-browser-action/2-catch-link-navigation/source.view/index.html b/2-ui/2-events/04-default-browser-action/2-catch-link-navigation/source.view/index.html index f0c934391..86ceeaecc 100644 --- a/2-ui/2-events/04-default-browser-action/2-catch-link-navigation/source.view/index.html +++ b/2-ui/2-events/04-default-browser-action/2-catch-link-navigation/source.view/index.html @@ -16,7 +16,7 @@
#contents

- How about to read Wikipedia or visit W3.org and learn about modern standards? + Que tal ler a Wikipedia ou visitar W3.org e aprender sobre os padrões modernos?

diff --git a/2-ui/2-events/04-default-browser-action/2-catch-link-navigation/task.md b/2-ui/2-events/04-default-browser-action/2-catch-link-navigation/task.md index 6ca456c2c..d11d18114 100644 --- a/2-ui/2-events/04-default-browser-action/2-catch-link-navigation/task.md +++ b/2-ui/2-events/04-default-browser-action/2-catch-link-navigation/task.md @@ -2,15 +2,15 @@ importance: 5 --- -# Catch links in the element +# Capture links no elemento -Make all links inside the element with `id="contents"` ask the user if they really want to leave. And if they don't then don't follow. +Faça com que todos os links dentro do elemento com `id="contents"` perguntem ao usuário se ele realmente quer sair. E, se ele não quiser, não navegue. -Like this: +Assim: [iframe height=100 border=1 src="solution"] -Details: +Detalhes: -- HTML inside the element may be loaded or regenerated dynamically at any time, so we can't find all links and put handlers on them. Use event delegation. -- The content may have nested tags. Inside links too, like `...`. +- O HTML dentro do elemento pode ser carregado ou regenerado dinamicamente em qualquer momento, então não podemos encontrar todos os links e colocar manipuladores neles. Use delegação de eventos. +- O conteúdo pode ter tags aninhadas. Dentro de links também, como `...`. diff --git a/2-ui/2-events/04-default-browser-action/3-image-gallery/solution.md b/2-ui/2-events/04-default-browser-action/3-image-gallery/solution.md index 5ff60b5c0..5a3c6a0b8 100644 --- a/2-ui/2-events/04-default-browser-action/3-image-gallery/solution.md +++ b/2-ui/2-events/04-default-browser-action/3-image-gallery/solution.md @@ -1 +1 @@ -The solution is to assign the handler to the container and track clicks. If a click is on the `` link, then change `src` of `#largeImg` to the `href` of the thumbnail. +A solução é atribuir o manipulador ao container e rastrear os cliques. Se um clique for no link ``, então mude o `src` de `#largeImg` para o `href` da miniatura. diff --git a/2-ui/2-events/04-default-browser-action/3-image-gallery/solution.view/index.html b/2-ui/2-events/04-default-browser-action/3-image-gallery/solution.view/index.html index 524bc7152..dd1d4e20a 100644 --- a/2-ui/2-events/04-default-browser-action/3-image-gallery/solution.view/index.html +++ b/2-ui/2-events/04-default-browser-action/3-image-gallery/solution.view/index.html @@ -2,31 +2,31 @@ - Gallery + Galeria -

Large image

+

Imagem grande

diff --git a/2-ui/2-events/04-default-browser-action/3-image-gallery/source.view/index.html b/2-ui/2-events/04-default-browser-action/3-image-gallery/source.view/index.html index c488ddcc2..3cbf104c4 100644 --- a/2-ui/2-events/04-default-browser-action/3-image-gallery/source.view/index.html +++ b/2-ui/2-events/04-default-browser-action/3-image-gallery/source.view/index.html @@ -2,31 +2,31 @@ - Gallery + Galeria -

Large image

+

Imagem grande

diff --git a/2-ui/2-events/04-default-browser-action/3-image-gallery/task.md b/2-ui/2-events/04-default-browser-action/3-image-gallery/task.md index f7571cc80..18c52f4eb 100644 --- a/2-ui/2-events/04-default-browser-action/3-image-gallery/task.md +++ b/2-ui/2-events/04-default-browser-action/3-image-gallery/task.md @@ -2,12 +2,12 @@ importance: 5 --- -# Image gallery +# Galeria de imagens -Create an image gallery where the main image changes by the click on a thumbnail. +Crie uma galeria de imagens onde a imagem principal muda ao clicar em uma miniatura. -Like this: +Assim: [iframe src="solution" height=600] -P.S. Use event delegation. +P.S. Use delegação de eventos. diff --git a/2-ui/2-events/04-default-browser-action/article.md b/2-ui/2-events/04-default-browser-action/article.md index cd815654f..b2d7834b3 100644 --- a/2-ui/2-events/04-default-browser-action/article.md +++ b/2-ui/2-events/04-default-browser-action/article.md @@ -1,43 +1,43 @@ -# Browser default actions +# Ações padrão do navegador -Many events automatically lead to certain actions performed by the browser. +Muitos eventos levam automaticamente a certas ações executadas pelo navegador. -For instance: +Por exemplo: -- A click on a link - initiates navigation to its URL. -- A click on a form submit button - initiates its submission to the server. -- Pressing a mouse button over a text and moving it - selects the text. +- Um clique em um link -- inicia a navegação para sua URL. +- Um clique no botão de envio de um formulário -- inicia o envio dele ao servidor. +- Pressionar o botão do mouse sobre um texto e movê-lo -- seleciona o texto. -If we handle an event in JavaScript, we may not want the corresponding browser action to happen, and want to implement another behavior instead. +Se tratarmos um evento em JavaScript, podemos não querer que a ação correspondente do navegador aconteça e, em vez disso, querer implementar outro comportamento. -## Preventing browser actions +## Prevenindo ações do navegador -There are two ways to tell the browser we don't want it to act: +Há duas formas de dizer ao navegador que não queremos que ele aja: -- The main way is to use the `event` object. There's a method `event.preventDefault()`. -- If the handler is assigned using `on` (not by `addEventListener`), then returning `false` also works the same. +- A forma principal é usar o objeto `event`. Há um método `event.preventDefault()`. +- Se o manipulador for atribuído usando `on` (não por `addEventListener`), então retornar `false` também funciona da mesma forma. -In this HTML, a click on a link doesn't lead to navigation; the browser doesn't do anything: +Neste HTML, um clique em um link não leva à navegação; o navegador não faz nada: ```html autorun height=60 no-beautify -Click here -or -here +Clique aqui +ou +aqui ``` -In the next example we'll use this technique to create a JavaScript-powered menu. +No próximo exemplo vamos usar essa técnica para criar um menu baseado em JavaScript. -```warn header="Returning `false` from a handler is an exception" -The value returned by an event handler is usually ignored. +```warn header="Retornar `false` de um manipulador é uma exceção" +O valor retornado por um manipulador de evento geralmente é ignorado. -The only exception is `return false` from a handler assigned using `on`. +A única exceção é `return false` de um manipulador atribuído usando `on`. -In all other cases, `return` value is ignored. In particular, there's no sense in returning `true`. +Em todos os outros casos, o valor de `return` é ignorado. Em particular, não faz sentido retornar `true`. ``` -### Example: the menu +### Exemplo: o menu -Consider a site menu, like this: +Considere um menu de site, como este: ```html ``` -Here's how it looks with some CSS: +Veja como fica com algum CSS: [iframe height=70 src="menu" link edit] -Menu items are implemented as HTML-links ``, not buttons ` + - ``` -Now, in addition to that context menu we'd like to implement document-wide context menu. +Agora, além desse menu de contexto, gostaríamos de implementar um menu de contexto no nível do documento. -Upon right click, the closest context menu should show up. +Ao clicar com o botão direito, o menu de contexto mais próximo deve aparecer. ```html autorun height=80 no-beautify run -

Right-click here for the document context menu

- +

Clique com o botão direito aqui para o menu de contexto do documento

+ ``` -The problem is that when we click on `elem`, we get two menus: the button-level and (the event bubbles up) the document-level menu. +O problema é que, quando clicamos em `elem`, obtemos dois menus: o do nível do botão e (o evento borbulha para cima) o do nível do documento. -How to fix it? One of solutions is to think like: "When we handle right-click in the button handler, let's stop its bubbling" and use `event.stopPropagation()`: +Como corrigir isso? Uma das soluções é pensar assim: "Quando tratarmos o clique direito no manipulador do botão, vamos parar seu bubbling" e usar `event.stopPropagation()`: ```html autorun height=80 no-beautify run -

Right-click for the document menu

- +

Clique com o botão direito para o menu do documento

+ ``` -Now the button-level menu works as intended. But the price is high. We forever deny access to information about right-clicks for any outer code, including counters that gather statistics and so on. That's quite unwise. +Agora o menu no nível do botão funciona como pretendido. Mas o preço é alto. Negamos para sempre o acesso à informação sobre cliques com o botão direito para qualquer código externo, incluindo contadores que coletam estatísticas e assim por diante. Isso não é nada sensato. -An alternative solution would be to check in the `document` handler if the default action was prevented? If it is so, then the event was handled, and we don't need to react on it. +Uma solução alternativa seria verificar no manipulador de `document` se a ação padrão foi prevenida. Se for o caso, então o evento foi tratado, e não precisamos reagir a ele. ```html autorun height=80 no-beautify run -

Right-click for the document menu (added a check for event.defaultPrevented)

- +

Clique com o botão direito para o menu do documento (adicionamos uma verificação de event.defaultPrevented)

+ ``` -Now everything also works correctly. If we have nested elements, and each of them has a context menu of its own, that would also work. Just make sure to check for `event.defaultPrevented` in each `contextmenu` handler. +Agora tudo também funciona corretamente. Se tivermos elementos aninhados, e cada um deles tiver seu próprio menu de contexto, isso também funcionaria. Só precisamos garantir que verificamos `event.defaultPrevented` em cada manipulador de `contextmenu`. -```smart header="event.stopPropagation() and event.preventDefault()" -As we can clearly see, `event.stopPropagation()` and `event.preventDefault()` (also known as `return false`) are two different things. They are not related to each other. +```smart header="event.stopPropagation() e event.preventDefault()" +Como podemos ver claramente, `event.stopPropagation()` e `event.preventDefault()` (também conhecido como `return false`) são duas coisas diferentes. Elas não têm relação uma com a outra. ``` -```smart header="Nested context menus architecture" -There are also alternative ways to implement nested context menus. One of them is to have a single global object with a handler for `document.oncontextmenu`, and also methods that allow us to store other handlers in it. +```smart header="Arquitetura de menus de contexto aninhados" +Há também formas alternativas de implementar menus de contexto aninhados. Uma delas é ter um único objeto global com um manipulador para `document.oncontextmenu`, e também métodos que nos permitem armazenar outros manipuladores nele. -The object will catch any right-click, look through stored handlers and run the appropriate one. +O objeto vai capturar qualquer clique direito, procurar entre os manipuladores armazenados e executar o apropriado. -But then each piece of code that wants a context menu should know about that object and use its help instead of the own `contextmenu` handler. +Mas então cada pedaço de código que quiser um menu de contexto deve saber sobre esse objeto e usar sua ajuda em vez do próprio manipulador de `contextmenu`. ``` -## Summary +## Resumo -There are many default browser actions: +Há muitas ações padrão do navegador: -- `mousedown` -- starts the selection (move the mouse to select). -- `click` on `` -- checks/unchecks the `input`. -- `submit` -- clicking an `` or hitting `key:Enter` inside a form field causes this event to happen, and the browser submits the form after it. -- `keydown` -- pressing a key may lead to adding a character into a field, or other actions. -- `contextmenu` -- the event happens on a right-click, the action is to show the browser context menu. -- ...there are more... +- `mousedown` -- inicia a seleção (mova o mouse para selecionar). +- `click` em `` -- marca/desmarca o `input`. +- `submit` -- clicar em um `` ou pressionar `key:Enter` dentro de um campo de formulário faz esse evento acontecer, e o navegador envia o formulário depois disso. +- `keydown` -- pressionar uma tecla pode levar à adição de um caractere em um campo, ou outras ações. +- `contextmenu` -- o evento acontece em um clique com o botão direito, a ação é mostrar o menu de contexto do navegador. +- ...há mais... -All the default actions can be prevented if we want to handle the event exclusively by JavaScript. +Todas as ações padrão podem ser prevenidas se quisermos tratar o evento exclusivamente com JavaScript. -To prevent a default action -- use either `event.preventDefault()` or `return false`. The second method works only for handlers assigned with `on`. +Para prevenir uma ação padrão -- use `event.preventDefault()` ou `return false`. O segundo método só funciona para manipuladores atribuídos com `on`. -The `passive: true` option of `addEventListener` tells the browser that the action is not going to be prevented. That's useful for some mobile events, like `touchstart` and `touchmove`, to tell the browser that it should not wait for all handlers to finish before scrolling. +A opção `passive: true` de `addEventListener` diz ao navegador que a ação não vai ser prevenida. Isso é útil para alguns eventos de dispositivos móveis, como `touchstart` e `touchmove`, para dizer ao navegador que ele não deve esperar que todos os manipuladores terminem antes de rolar. -If the default action was prevented, the value of `event.defaultPrevented` becomes `true`, otherwise it's `false`. +Se a ação padrão foi prevenida, o valor de `event.defaultPrevented` se torna `true`, caso contrário é `false`. -```warn header="Stay semantic, don't abuse" -Technically, by preventing default actions and adding JavaScript we can customize the behavior of any elements. For instance, we can make a link `
` work like a button, and a button `