diff options
Diffstat (limited to 'files/pt-br/web/guide/events')
6 files changed, 892 insertions, 0 deletions
diff --git a/files/pt-br/web/guide/events/criando_e_disparando_eventos/index.html b/files/pt-br/web/guide/events/criando_e_disparando_eventos/index.html new file mode 100644 index 0000000000..632b54df75 --- /dev/null +++ b/files/pt-br/web/guide/events/criando_e_disparando_eventos/index.html @@ -0,0 +1,145 @@ +--- +title: Criando e disparando eventos +slug: Web/Guide/Events/criando_e_disparando_eventos +tags: + - Avançado + - DOM + - Guía + - JavaScript + - eventos +translation_of: Web/Guide/Events/Creating_and_triggering_events +--- +<p>Este artigo demonstra como criar e disparar eventos DOM. Tais eventos são comumente chamados <strong>eventos sintéticos</strong>, oposto aos eventos disparados pelo próprio navegador.</p> + +<h2 id="Criando_eventos_customizados">Criando eventos customizados</h2> + +<p>Eventos podem ser criados com o construtor <a href="/en-US/docs/Web/API/Event"><code>Event</code></a> da seguinte forma:</p> + +<pre class="brush: js">var event = new Event('build'); + +// Ouve pelo evento. +elem.addEventListener('build', function (e) { ... }, false); + +// Dispara o evento. +elem.dispatchEvent(event);</pre> + +<p>Este construtor é suportado na maioria dos navegadores modernos (com o Internet Explorer sendo exceção). Para uma abordagem mais verbosa (a qual é suportada pelo Internet Explorer), veja <a href="#The_old-fashioned_way" title="#The_old-fashioned_way">a forma antiga</a> abaixo.</p> + +<h3 id="Adicionando_dados_customizados_–_CustomEvent()">Adicionando dados customizados – CustomEvent()</h3> + +<p>Para adicionar mais dados ao objeto do evento, usa-se a interface <a href="/en-US/docs/Web/API/CustomEvent">CustomEvent</a>, a qual possui a propriedade <u><strong>detail</strong></u> que pode ser utilizada para fornecer dados customizados.</p> + +<p><span style="line-height: 1.5;">Por exemplo, o evento pode ser criado da seguinte forma:</span></p> + +<pre class="brush: js">var event = new CustomEvent('build', { 'detail': elem.dataset.time });</pre> + +<p>Isso permitirá que você acesse dados customizados no listener do evento:</p> + +<pre class="brush: js">function eventHandler(e) { + console.log('The time is: ' + e.detail); +} +</pre> + +<h3 id="A_forma_antiga">A forma antiga</h3> + +<p>A forma antiga de criar eventos possui uma abordagem mais verbosa, tendo APIs inspiradas em Java. Abaixo temos um exemplo:</p> + +<pre class="brush: js">// Cria o evento. +var event = <a href="/en-US/docs/Web/API/Document/createEvent">document.createEvent</a>('Event'); + +// Define que o nome do evento é 'build'. +event.initEvent('build', true, true); + +// Ouve pelo evento. +elem.addEventListener('build', function (e) { + // e.target é igual a elem, neste caso +}, false); + +// O alvo do evento pode ser qualquer instância de Element ou EventTarget. +elem.dispatchEvent(event); + +</pre> + +<h2 id="Disparando_eventos_nativos">Disparando eventos nativos</h2> + +<p>Este exemplo mostra a simulação de um clique (isto é, gera um um clique de forma programatica) sobre um checkbox usando métodos DOM. <a class="external" href="http://developer.mozilla.org/samples/domref/dispatchEvent.html">Veja o exemplo em ação.</a></p> + +<pre class="brush: js">function simulateClick() { + var event = new MouseEvent('click', { + 'view': window, + 'bubbles': true, + 'cancelable': true + }); + + var cb = document.getElementById('checkbox'); + var cancelled = !cb.dispatchEvent(event); + + if (cancelled) { + // Um listener invocou o método preventDefault. + alert("Cancelado"); + } else { + // Nenhum listener invocou o método preventDefault. + alert("Não cancelado"); + } +}</pre> + +<h2 id="Browser_compatibility" name="Browser_compatibility" style="line-height: 30px; font-size: 2.14285714285714rem;">Compatibilidade entre navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th style="line-height: 16px;">Feature</th> + <th style="line-height: 16px;">Chrome</th> + <th style="line-height: 16px;">Firefox (Gecko)</th> + <th style="line-height: 16px;">Edge</th> + <th style="line-height: 16px;">Internet Explorer</th> + <th style="line-height: 16px;">Opera</th> + <th style="line-height: 16px;">Safari (WebKit)</th> + </tr> + <tr> + <td><code>construtor Event()</code></td> + <td>15</td> + <td>11</td> + <td>{{CompatVersionUnknown}}</td> + <td>11</td> + <td>11.60</td> + <td>6</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th style="line-height: 16px;">Feature</th> + <th style="line-height: 16px;">Android</th> + <th style="line-height: 16px;">Firefox Mobile (Gecko)</th> + <th style="line-height: 16px;">IE Mobile</th> + <th style="line-height: 16px;">Opera Mobile</th> + <th style="line-height: 16px;">Safari Mobile</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>6</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Veja_também">Veja também</h2> + +<ul> + <li>{{domxref("document.createEvent()")}}</li> + <li>{{domxref("Event.initEvent()")}}</li> + <li>{{domxref("EventTarget.dispatchEvent()")}}</li> + <li>{{domxref("EventTarget.addEventListener()")}}</li> +</ul> diff --git a/files/pt-br/web/guide/events/event_handlers/index.html b/files/pt-br/web/guide/events/event_handlers/index.html new file mode 100644 index 0000000000..f558992d27 --- /dev/null +++ b/files/pt-br/web/guide/events/event_handlers/index.html @@ -0,0 +1,164 @@ +--- +title: DOM onevent handlers +slug: Web/Guide/Events/Event_handlers +translation_of: Web/Guide/Events/Event_handlers +--- +<p>A plataforma web oferece várias maneiras de trabalhar com o <span class="seoSummary"><a href="/en-US/docs/Web/Events">DOM events</a>. </span>Duas abordagens comuns são:<span class="seoSummary"> {{domxref("EventTarget.addEventListener", "addEventListener()")}} e o específico <code>on<em>event</em></code> que dispara um evento.</span> Este artigo se concentra em como o último funciona.</p> + +<h2 id="Registering_onevent_handlers">Registering onevent handlers</h2> + +<p>The <strong><code>on<em>event</em></code></strong> handlers are properties on certain DOM elements to manage how that element reacts to events. Elements can be interactive (links, buttons, images, forms, and so forth) or non-interactive (such as the base <code><body></code> element). Events are actions like:</p> + +<ul> + <li>Being clicked</li> + <li>Detecting pressed keys</li> + <li>Getting focus</li> +</ul> + +<p>The on-event handler is usually named with the event it reacts to, like <code>on<em>click</em></code>, <code>on<em>keypress</em></code>, <code>on<em>focus</em></code>, etc.</p> + +<p>You can specify an <code>on<em><…></em></code> event handler for a particular event (such as {{event("click")}}) for a given object in different ways:</p> + +<ul> + <li>Adding an HTML {{Glossary("attribute")}} named <code>on<em><eventtype></em></code>:<br> + <code><button <strong>onclick="handleClick()"</strong>></code>,</li> + <li>Or by setting the corresponding {{Glossary("property/JavaScript", "property")}} from JavaScript:<br> + <code>document.querySelector("button")<strong>.onclick = function(event) { … }</strong></code>.</li> +</ul> + +<p>An <code>on<em>event</em></code> event handler property serves as a placeholder of sorts, to which a single event handler can be assigned. In order to allow multiple handlers to be installed for the same event on a given object, you can call its {{domxref("EventTarget.addEventListener", "addEventListener()")}} method, which manages a list of handlers for the given event on the object. A handler can then be removed from the object by calling its {{domxref("EventTarget.removeEventListener", "removeEventListener()")}} function.</p> + +<p>When an event occurs that applies to an element, each of its event handlers is called to allow them to handle the event, one after another. You don't need to call them yourself, although you can do so in many cases to easily simulate an event taking place. For example, given a button object <code>myButton</code>, you can do <code>myButton.onclick(myEventObject)</code> to call the event handler directly. If the event handler doesn't access any data form the event object, you can leave out the event when calling <code>onclick()</code>.</p> + +<p>This continues until every handler has been called, unless one of the event handlers explicitly halts the processing of the event by calling {{domxref("Event.stopPropagation", "stopPropagation()")}} on the event object itself.</p> + +<h3 id="Non-element_objects">Non-element objects</h3> + +<p>Event handlers can also be set with properties on non-element objects that generate events, like {{ domxref("window") }}, {{ domxref("document") }}, {{ domxref("XMLHttpRequest") }}, and others. For example, for the <code>progress</code> event on instances of <code>XMLHttpRequest</code>:</p> + +<pre class="brush: js notranslate">const xhr = new XMLHttpRequest(); +xhr.onprogress = function() { … };</pre> + +<h2 id="HTML_onevent_attributes">HTML onevent attributes</h2> + +<p>HTML elements have attributes named <code>on<em>event</em></code> which can be used to register a handler for an event directly within the HTML code. When the element is built from the HTML, the value of its <code>on<em>event</em></code> attributes are copied to the DOM object that represents the element, so that accessing the attributes' values using JavaScript will get the value set in the HTML.</p> + +<p>Further changes to the HTML attribute value can be done via the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute"><code>setAttribute</code> </a>method; Making changes to the JavaScript property will have no effect.</p> + +<h3 id="HTML">HTML</h3> + +<p>Given this HTML document:</p> + +<pre class="brush: html notranslate"><p>Demonstrating quirks of <code>on<em>event</em></code> HTML attributes on + <a onclick="log('Click!')">these three words</a>. +</p> + +<div></div></pre> + +<h3 id="JavaScript">JavaScript</h3> + +<p>Then this JavaScript demonstrates that the value of the HTML attribute is unaffected by changes to the JavaScript object's property.</p> + +<pre class="brush: js notranslate">let logElement = document.querySelector('div'); +let el = document.querySelector("a"); + +function log(msg) { logElement.innerHTML += `${msg}<br>` }; +function anchorOnClick(event) { log("Changed onclick handler") }; + +// Original Handler +log(`Element's onclick as a JavaScript property: <code> ${el.onclick.toString()} </code>`); + +//Changing handler using .onclick +log('<br>Changing onclick handler using <strong> onclick property </strong> '); + +el.onclick = anchorOnClick; + +log(`Changed the property to: <code> ${el.onclick.toString()} </code>`); +log(`But the HTML attribute is unchanged: <code> ${el.getAttribute("onclick")} </code><br>`); + +//Changing handler using .setAttribute +log('<hr/><br> Changing onclick handler using <strong> setAttribute method </strong> '); +el.setAttribute("onclick", 'anchorOnClick(event)'); + +log(`Changed the property to: <code> ${el.onclick.toString()} </code>`); +log(`Now even the HTML attribute has changed: <code> ${el.getAttribute("onclick")} </code><br>`);</pre> + +<h3 id="Result">Result</h3> + +<p>{{ EmbedLiveSample('HTML_onevent_attributes', '', '', '', 'Web/Guide/Events/Event_handlers') }}</p> + +<p>For historical reasons, some attributes/properties on the {{HTMLElement("body")}} and {{HTMLElement("frameset")}} elements instead set event handlers on their parent {{domxref("Window")}} object. (The HTML specification names these: <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onblur">onblur</a></code>, <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onerror">onerror</a></code>, <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onfocus">onfocus</a></code>, <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onload">onload</a></code>, and <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onscroll">onscroll</a></code>.)</p> + +<h3 id="Event_handlers_parameters_this_binding_and_the_return_value">Event handler's parameters, <code>this</code> binding, and the return value</h3> + +<p>When the event handler is specified as <strong>an HTML attribute</strong>, the specified code is wrapped into a function with <strong>the following parameters</strong>:</p> + +<ul> + <li><code>event</code> — for all event handlers except {{domxref("GlobalEventHandlers.onerror", "onerror")}}.</li> + <li><code>event</code>, <code>source</code>, <code>lineno</code>, <code>colno</code>, and <code>error</code> for the {{domxref("GlobalEventHandlers.onerror", "onerror")}} event handler. Note that the <code>event</code> parameter actually contains the error message as a string.</li> +</ul> + +<p>When the event handler is invoked, the <code>this</code> keyword inside the handler is set to the DOM element on which the handler is registered. For more details, see <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this#In_an_inline_event_handler">the <code>this</code> keyword documentation</a>.</p> + +<p>The return value from the handler determines if the event is canceled. The specific handling of the return value depends on the kind of event; for details, see <a href="https://html.spec.whatwg.org/multipage/webappapis.html#the-event-handler-processing-algorithm">"The event handler processing algorithm" in the HTML specification</a>.</p> + +<h3 id="When_the_event_handler_is_invoked">When the event handler is invoked</h3> + +<div class="blockIndicator note"> +<p>TBD (non-capturing listener)</p> +</div> + +<h3 id="Terminology">Terminology</h3> + +<p>The term <strong>event handler</strong> may refer to:</p> + +<ul> + <li>Any function or object that is registered to be notified of events</li> + <li>Or more specifically, to the mechanism of registering event listeners via <code>on…</code> attributes in HTML or properties in Web APIs, such as <code><button onclick="alert(this)"></code> or <code>window.onload = function() { … }</code>.</li> +</ul> + +<p>When discussing the various methods of listening to events:</p> + +<ul> + <li><strong>Event listener</strong> refers to a function or object registered via {{domxref("EventTarget.addEventListener()")}}</li> + <li><strong>Event handler</strong> refers to a function registered via <code>on…</code> attributes or properties</li> +</ul> + +<h2 id="Specifications" name="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', 'webappapis.html#event-handler-attributes', 'event handlers')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', 'webappapis.html#event-handler-attributes', 'event handlers')}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_Compatibility" name="Browser_Compatibility">Browser compatibility</h2> + +<h4 id="Detecting_the_presence_of_event_handler_properties">Detecting the presence of event handler properties</h4> + +<p>You can detect the presence of an event handler property with the JavaScript <a href="/en-US/JavaScript/Reference/Operators/in" title="en/JavaScript/Reference/Operators/in"><code>in</code></a> operator. For example:</p> + +<pre class="brush: js notranslate">if ("onsomenewfeature" in window) { + /* do something amazing */ +} +</pre> + +<h4 id="Event_handlers_and_prototypes">Event handlers and prototypes</h4> + +<p>You can't set or access the values of any IDL-defined attributes on DOM prototype objects. That means you can't, for example, change <code>Window.prototype.onload</code>. In the past, event handlers (<code>onload</code>, etc.) weren't implemented as IDL attributes in Gecko, so you were able to do this for those. Now you can't. This improves compatibility.</p> diff --git a/files/pt-br/web/guide/events/index.html b/files/pt-br/web/guide/events/index.html new file mode 100644 index 0000000000..65b5775a16 --- /dev/null +++ b/files/pt-br/web/guide/events/index.html @@ -0,0 +1,36 @@ +--- +title: Event developer guide +slug: Web/Guide/Events +tags: + - DOM + - Event + - Guide + - NeedsTranslation + - TopicStub + - events +translation_of: Web/Guide/Events +--- +<p>{{draft()}}</p> +<p>Events refers both to a design pattern used for the asynchronous handling of various incidents which occur in the lifetime of a web page and to the naming, characterization, and use of a large number of incidents of different types.</p> +<p>The <a href="/en-US/docs/Web/Guide/API/DOM/Events/Overview_of_Events_and_Handlers">overview page</a> provides an introduction to the design pattern and a summary of the types of incidents which are defined and reacted to by modern web browsers.</p> +<p>The <a href="/en-US/docs/Web/Guide/API/DOM/Events/Creating_and_triggering_events">custom events page</a> describes how the event code design pattern can be used in custom code to define new event types emitted by user objects, register listener functions to handle those events, and trigger the events in user code.</p> +<p>The remaining pages describe how to use events of different kinds defined by web browsers. Unfortunately, these events have been defined piece by piece as web browsers have evolved so that there is no satisfying systematic characterization of the events built-in or defined by modern web browsers.</p> +<p>The <strong>device</strong> on which the web browser is running can trigger events, for example due to a change in its position and orientation in the real world, as discussed partially by the <a href="/en-US/docs/Web/Guide/API/DOM/Events/Orientation_and_motion_data_explained">page on orientation coordinate systems</a> and the <a href="/en-US/docs/Web/Guide/API/DOM/Events/Using_device_orientation_with_3D_transforms">page on the use of 3D transforms</a>. That is different, but similar, to the change in device vertical orientation. </p> +<p>The <strong>window</strong> in which the browser is displayed which might trigger events, for example, change size if the user maximizes the window or otherwise changes it.</p> +<p>The <strong>process</strong> loading of a web page might trigger events in response to the completion of different steps in the downloading, parsing, and rendering of the web page for display to the user.</p> +<p>The <strong>user interaction</strong> with the web page contents might trigger events. The events triggered by user interaction evolved during the early years of browser design and include a complicated system defining the sequence in which events will be called and the manner in which that sequence can be controlled. The different types of user interaction driven events include:</p> +<ul> + <li>the original 'click' event,</li> + <li>mouse events,</li> + <li><a href="/en-US/docs/Web/Guide/API/DOM/Events/Mouse_gesture_events">mouse gesture events</a>, and</li> + <li>both <a href="/en-US/docs/Web/Guide/API/DOM/Events/Touch_events">touch events</a> and the earlier, but deprecated, <a href="/en-US/docs/Web/Guide/API/DOM/Events/Touch_events_(Mozilla_experimental)">mozilla experimental touch events</a>.</li> +</ul> +<p>The <strong>modification of the web page</strong> in structure or content might trigger some events, as is explained in the <a href="/en-US/docs/Web/Guide/API/DOM/Events/Mutation_events">mutation events page</a>, but the use of these events has been deprecated in favour of the lighter <a href="/en-US/docs/Web/API/MutationObserver">Mutation Observer</a> approach.</p> +<p>The <strong>media streams</strong> embedded in the HTML documents might trigger some events, as explained in the <a href="/en-US/docs/Web/Guide/API/DOM/Events/Media_events">media events</a> page.</p> +<p>The <strong>network requests</strong> made by a web page might trigger some events.</p> +<p>There are many other sources of events defined by web browsers for which pages are not yet available in this guide.</p> +<div class="note"> + <p>Note: This Event Developer Guide needs substantial work. The structure needs to be reorganized and the pages rewritten. Our hope is that everything you need to know about events will go under here.</p> +</div> +<h2 id="Docs">Docs</h2> +<p>{{LandingPageListSubpages}}</p> diff --git a/files/pt-br/web/guide/events/mutation_events/index.html b/files/pt-br/web/guide/events/mutation_events/index.html new file mode 100644 index 0000000000..582670fb98 --- /dev/null +++ b/files/pt-br/web/guide/events/mutation_events/index.html @@ -0,0 +1,62 @@ +--- +title: Mutation events +slug: Web/Guide/Events/Mutation_events +translation_of: Web/Guide/Events/Mutation_events +--- +<p>{{deprecated_header()}}</p> + +<p><strong>Mutation events</strong> fornecem um mecanismo, para uma página web ou uma extensão, de notificação sobre as alterações feitas no DOM. <span style="background-color: #ffff00;">Utilize ao invés, se possível, <a href="/en-US/docs/Web/API/MutationObserver" title="/en-US/docs/Web/API/MutationObserver">Mutation Observers</a>.</span></p> + +<h2 id="Prefácio">Prefácio</h2> + +<p>Os eventos de mutação foram marcados como em desuso na <a class="external" href="http://www.w3.org/TR/DOM-Level-3-Events/#events-mutationevents">DOM Events specification</a> pelo fato do projeto da API ser falho (veja detalhes no "DOM Mutation Events Replacement: The Story So Far / Existing Points of Consensus" publicado em <span id="to"><a class="external" href="http://lists.w3.org/Archives/Public/public-webapps/2011JulSep/0779.html">public-webapps</a>)</span>.</p> + +<p id="Replacement.3A_mutation_observers"><a href="/en-US/docs/Web/API/MutationObserver">Mutation Observers</a> são a proposta de substituição para eventos de mutação no DOM4. Eles devem ser incluídos no Firefox 14 e <a class="external" href="http://updates.html5rocks.com/2012/02/Detect-DOM-changes-with-Mutation-Observers" title="http://updates.html5rocks.com/2012/02/Detect-DOM-changes-with-Mutation-Observers">Chrome 18</a>.</p> + +<p>As razões práticas para evitar os eventos de mutação são <strong>problemas de desempenho</strong> e suporte <strong>cross-browser.</strong></p> + +<h3 id="Performance">Performance</h3> + +<p>Adicionando listeners de mutação do DOM a um documento <a class="external" href="http://groups.google.com/group/mozilla.dev.platform/browse_thread/thread/2f42f1d75bb906fb?pli=1" rel="external" title="http://groups.google.com/group/mozilla.dev.platform/browse_thread/thread/2f42f1d75bb906fb?pli=1">degrada o desempenho profundamente</a> de outras modificações DOM para esse documento (tornando-os 1.5 - 7 vezes mais lento!). Além disso, remover os listeners não reverte o dano.</p> + +<p>O efeito de desempenho é <a class="link-https" href="https://groups.google.com/forum/#!topic/mozilla.dev.platform/UH2VqFQRTDA" title="https://groups.google.com/forum/#!topic/mozilla.dev.platform/UH2VqFQRTDA">limitado aos documentos que têm os listeners de evento de mutação</a>.</p> + +<h3 id="Suporte_cross-browser">Suporte cross-browser</h3> + +<p>Esses eventos não são implementados de forma consistente entre os diferentes navegadores, por exemplo:</p> + +<ul> + <li>IE anteriores à versão 9 não suportavam os eventos de mutação por completo e em alguns aspectos não implementa corretamente na versão 9 (<a class="external" href="http://help.dottoro.com/ljmcxjla.php" title="http://help.dottoro.com/ljmcxjla.php">por exemplo, DOMNodeInserted</a>)</li> + <li>WebKit não suporta DOMAttrModified (veja <a class="link-https" href="https://bugs.webkit.org/show_bug.cgi?id=8191" title="https://bugs.webkit.org/show_bug.cgi?id=8191">webkit bug 8191</a> e <a class="external" href="http://about.silkapp.com/page/Mutation%20Events:%20What%20Happen" title="http://about.silkapp.com/page/Mutation%20Events:%20What%20Happen">the workaround</a>)</li> + <li>"mutation name events", por exemplo DOMElementNameChanged e DOMAttributeNameChanged não são suportados no Firefox (a partir da versão 11), e provavelmente em outros navagedores também.</li> + <li>...</li> +</ul> + +<p>Dottoro <a class="external" href="http://help.dottoro.com/ljfvvdnm.php#additionalEvents" title="http://help.dottoro.com/ljfvvdnm.php#additionalEvents">suporte a eventos de mutação nos navegadores</a>.</p> + +<h2 id="Lista_de_mutation_events">Lista de mutation events</h2> + +<p>Listado a seguir todos os eventos de mutação, como definido no <a class="external" href="http://www.w3.org/TR/DOM-Level-3-Events/#events-mutationevents" title="http://www.w3.org/TR/DOM-Level-3-Events/#events-mutationevents">DOM Level 3 Events specification</a>:</p> + +<ul> + <li><code>DOMAttrModified</code></li> + <li><code>DOMAttributeNameChanged</code></li> + <li><code>DOMCharacterDataModified</code></li> + <li><code>DOMElementNameChanged</code></li> + <li><code>DOMNodeInserted</code></li> + <li><code>DOMNodeInsertedIntoDocument</code></li> + <li><code>DOMNodeRemoved</code></li> + <li><code>DOMNodeRemovedFromDocument</code></li> + <li><code>DOMSubtreeModified</code></li> +</ul> + +<h2 id="Uso">Uso</h2> + +<p>Você pode registrar um listener para eventos de mutação usando <a href="/en/DOM/element.addEventListener" title="en/DOM/element.addEventListener">element.addEventListener</a>, como mostrado a seguir:</p> + +<pre><code>element.addEventListener("DOMNodeInserted", function (event) {</code> + // ... +<code>}, false);</code> +</pre> + +<p>O objeto event é transmitido para o listener em um {{ domxref("MutationEvent") }} (veja <a class="external" href="http://www.w3.org/TR/DOM-Level-3-Events/#events-MutationEvent" title="http://www.w3.org/TR/DOM-Level-3-Events/#events-MutationEvent">sua definição na especificação</a>) para a maioria dos eventos, e {{ domxref("MutationNameEvent") }} para <code>DOMAttributeNameChanged</code> e <code>DOMElementNameChanged</code>.</p> diff --git a/files/pt-br/web/guide/events/overview_of_events_and_handlers/index.html b/files/pt-br/web/guide/events/overview_of_events_and_handlers/index.html new file mode 100644 index 0000000000..2593d5641e --- /dev/null +++ b/files/pt-br/web/guide/events/overview_of_events_and_handlers/index.html @@ -0,0 +1,132 @@ +--- +title: Uma visão geral sobre Events e Handlers +slug: Web/Guide/Events/Overview_of_Events_and_Handlers +translation_of: Web/Guide/Events/Overview_of_Events_and_Handlers +--- +<div class="summary"> +<p>Este artigo apresenta uma visão geral sobre o design pattern usado para reagir a alterações que ocorrem quando o navegador acessa uma página, e dá um resumo sobre como os navegadores modernos reagem a eles.</p> +</div> + +<p>Eventos e a manipulação de eventos fornecem uma técnica essencial em JavaScript para reagir a algum incidente quando o navegador acessa uma página, incluindo eventos de preparação para exibir a página, ou interação com algum conteúdo da página que estejam relacionados com o dispositivo onde o navagador está rodando, e muitas outras, como reprodução de áudio ou vídeo.</p> + +<p>A manipulação de eventos tornou-se imprescindível com a evolução e mudança na arquitetura de renderização dos navegadores em relação a forma de busca e carregamento de informações na página. No início, os navegadores esperavam e recebiam os dados e recursos associados a página para analisar, processar e apresentar a página ao usuário. A página permanecia inalterada até uma requisição para um novo link. Atualmente, com a mudança para páginas dinâmicas, os navegadores estão sempre em um loop contínuo, processando, desenhando, apresentando conteúdo e esperando de algum novo evento. Os gatilhos (triggers) de evento podem ser a conclusão do carregamento de um arquivo na rede, por exemplo, uma imagem que agora pode ser mostrada na tela, a conclusão da análise de um recurso pelo navegador, o processamento do conteúdo HTML de uma página, a interação de um usuário com o conteúdo da página, com o clique em um botão. Douglas Crockford explica essa mudança de maneira eficaz em sua palestra, <em>An Inconvenient API: The Theory of the DOM.</em></p> + +<p>With the change to dynamic page rendering, browsers loop continuously between processing, drawing, presenting content, and waiting for some new event trigger. Event triggers include the completion of the loading of a resource on the network <em>e.g.,</em> downloads an image that can now be drawn on the screen, the completion of parsing a resource by the browser <em>e.g.</em>, processes the HTML content of a page, the interaction of a user with the contents of the page <em>e.g.,</em> clicks a button. Douglas Crockford explains this change effectively in several lectures, notably his talk, <em>An Inconvenient API: The Theory of the DOM,</em> which shows the change in flow from the original browser flow</p> + +<div style="margin: 0 auto; width: 68%;"><img alt="A comparison of the sequential and event-driven browser load sequences." src="https://mdn.mozillademos.org/files/6641/Browser_sequence_comparitive.svg" style="height: 454px; width: 1857px;"></div> + +<p>to the event driven browser. The latter approach changes the last steps from a single flow into a perpetual loop, where waiting for and handling the incidence of new events follows painting. The innovation of the dynamic approach allows for a page to be partially rendered even when the browser has not finished retrieving all resources; this approach also allows for event driven actions, which JavaScript leverages. (The talk is available from several sources, including <a href="http://www.youtube.com/watch?v=Y2Y0U-2qJMs">this one</a>.) Currently, all execution environments for JavaScript code use events and event handling.</p> + +<h2 id="The_event_design_pattern">The event design pattern</h2> + +<p>The event system, at its core, is simply a programming design pattern. The pattern starts with an agreement over a kind of event and:</p> + +<ul> + <li>the name String used for the event,</li> + <li>the type of the data structure used to represent the key properties of that event, and</li> + <li>the JavaScript object which will 'emit' that event.</li> +</ul> + +<p>The pattern is implemented by</p> + +<ul> + <li>defining a JavaScript function which takes as an argument the data structure which was agreed upon, and</li> + <li>registering the function using the name String with the object which will emit the event.</li> +</ul> + +<p>The function is said to be a 'listener' or a 'handler' with both names used interchangeably. This pattern can easily be followed using completely custom code, as explained in the <a href="/en-US/docs/Web/Guide/API/DOM/Events/Creating_and_triggering_events">article on custom events</a>. The pattern is also used by modern web browsers which define many events emitted in response to user input or browser activity.</p> + +<p>Modern web browsers follow the event pattern using a standardized approach. Browsers use as the data structure for the properties of the event, an object derived from the <code>EventPrototype</code> object. Browsers use as the registration method for the function which will handle those data structures a method called <code>addEventListener</code> which expects as arguments a string event type name and the handler function. Finally, browsers define a large number of objects as event emitters and define a wide variety of event types generated by the objects.</p> + +<h2 id="Button_Event_Handler" name="Button_Event_Handler">Button Event Handler Demo</h2> + +<p>For example, browser <code>button</code> elements are intended to emit events named <code>'click'</code> in response to a mouse click or, when displayed in touch sensitive surfaces, to a finger tap. We could define in the HTML page a <code>button</code> as:</p> + +<pre class="brush: html notranslate"><button id="buttonOne">Click here to emit a 'click' event</button></pre> + +<p>and, in our JavaScript code, we could first define a function to listen to that <code>'click'</code> event:</p> + +<pre class="brush: js notranslate">var example_click_handler = function (ev){ + var objKind = (ev instanceof Event) ? "EventPrototype" : "ObjectPrototype"; + alert("We got a click event at " + ev.timeStamp + " with an argument object derived from: " + objKind ); +};</pre> + +<p>and second register our function with the the <code>Button</code> object, either on the scripting side using the DOM (Document Object Model) representation of the HTML page:</p> + +<pre class="brush: js notranslate">var buttonDOMElement = document.querySelector('#buttonOne'); +buttonDOMElement.addEventListener('click', example_click_handler);</pre> + +<p>or within the HTML page by adding the function as the value of the <code>'onclick'</code> attribute, although this second approach is usually only used in very simple web pages.</p> + +<p>{{ EmbedLiveSample('Button_Event_Handler') }}</p> + +<p>This code relies on the agreement that there is a kind of event called <code>'click'</code> which will call any listener (or 'handler') function with an <code>Event</code> object argument (actually, in this case a derivative <code>MouseEvent</code> object) and which will be fired by HTML <code>button</code> elements after user interaction. The code has no visible effect until a user interacts with the button either by placing the mouse pointer over the HTML button and clicking on the left mouse button or by placing a finger or stylus of some kind on the screen above the HTML button; when that happens, the <code>buttonDOMElement</code> JavaScript object would call the <code>example_click_handler</code> function with an <code>Event</code> object as an argument. The function, in turn, would perform whatever action was chosen by the programmer, in this case to open an HTML alert dialog. Note that the handler has access to the <code>ev</code> object since it is passed as an argument; the object has information about the event, notably the time at which the event occurred.</p> + +<p>As a second example, much modern JavaScript integrated into web pages is wrapped into an event function call to ensure that the code is only executed when the HTML has been processed and is available for alteration or decoration. For example, code might be attached as:</p> + +<pre class="brush: js notranslate">var funcInit = function(){ + // user code goes here and can safely address all the HTML elements from the page + // since the document has successfully been 'loaded' +} +document.addEventListener('DOMContentLoaded', funcInit); +</pre> + +<p>so that this code will only be executed after the <code>document</code> object emits the <code>'DOMContentLoaded'</code> event because the HTML has been parsed and Javasript objects created representing each of the nodes of the HTML document. Note that in this example, the code does not even name the event argument to the function because the code never needs to use the data structure describing the event; rather, the code merely needs to wait to run until after then event has happened.</p> + +<p>The pattern is therefore easy to learn and implement. The difficulty with events comes from learning the wide variety of events which are generated in modern web browsers. There is also some subtlety in learning how to write the handler functions since such code works asynchronously and potentially will run repeatedly but in slightly different situations.</p> + +<h2 id="Notable_events">Notable events</h2> + +<p>Web browsers define a large number of events so it is not practical to list them all. The <a href="/en-US/docs/Web/Reference/Events">Event Reference</a> attempts to maintain a list of the standard Events used in modern web browsers.</p> + +<p>In general, we can distinguish events of different kinds based on the object emitting the event including:</p> + +<ul> + <li>the <code>window</code> object, such as due to resizing the browser,</li> + <li>the <code>window.screen</code> object, such as due to changes in device orientation,</li> + <li>the <code>document</code> object, including the loading, modification, user interaction, and unloading of the page,</li> + <li>the objects in the DOM (document object model) tree including user interactions or modifications,</li> + <li>the <code>XMLHttpRequest</code> objects used for network requests, and</li> + <li>the media objects such as <code>audio</code> and <code>video</code>, when the media stream players change state.</li> +</ul> + +<p>although this list is currently incomplete.</p> + +<p>Some notable events are:</p> + +<div class="note"> +<p><strong>Note:</strong> This list of events will need work to make relevant; that work is awaiting some global reorganization work on the documents. This will also need finding a good explanation of the events involved during page loading, such as discussed partially in <em><a href="http://ablogaboutcode.com/2011/06/14/how-javascript-loading-works-domcontentloaded-and-onload">this web page</a> or in <a href="http://stackoverflow.com/questions/1795438/load-and-execution-sequence-of-a-web-page">this Stack Overflow question</a>. </em></p> +</div> + +<ul> + <li>the global object <a href="/en-US/docs/Web/API/Window"><code>window</code></a> emits an event called <a href="/en-US/docs/Web/Reference/Events/load_(ProgressEvent)"><code>'load'</code></a> when the page has finished rendering, meaning that all resources have been downloaded and acted upon, so that the scripts have been run and the images displayed,</li> + <li>the global object <a href="/en-US/docs/Web/API/Window"><code>window</code></a> emits an event called <a href="/en-US/docs/Web/Reference/Events/resize"><code>'resize'</code></a> when the height or the width of the browser window is changed by a user,</li> + <li>the DOM object <a href="/en-US/docs/Web/API/Document"><code>document</code></a> representing the HTML document emits an event called<code> <a href="/en-US/docs/Web/Reference/Events/DOMContentLoaded">'DOMContentLoaded'</a></code> when the document has finished loading,</li> + <li>the DOM node objects such as <a href="/en-US/docs/Web/HTML/Element/div"><code>div</code></a> or <a href="/en-US/docs/Web/HTML/Element/button"><code>button</code></a> emit an event called <a href="/en-US/docs/Web/Reference/Events/click"><code>'click'</code></a> when the user presses the mouse button while the mouse pointer is on top of the DOM node in the HTML page.</li> +</ul> + + + +<h2 id="The_Event_object_hierarchy">The Event object hierarchy</h2> + +<p>The web browser defines many events of different kinds. Each definition includes, as the data structure passed to the handler function, an object which inherits from the <code>EventPrototype</code> object.</p> + +<p>A partial diagram of the class hierarchy of event objects is:</p> + +<div class="note"> +<p><strong>Note:</strong> This diagram is incomplete.</p> +</div> + +<p><img alt="" src="https://mdn.mozillademos.org/files/6633/Js_Event_Object_Hierarchy.svg" style="height: 496px; width: 1417px;"></p> + +<p>The Web API Documentation contains <a href="/en-US/docs/Web/API/Event">a page defining the Event object</a> which also includes the known DOM event subclasses of the <code>Event</code> object.</p> + +<h2 id="Documents">Documents</h2> + +<p>Three sources on the MDN (Mozilla Developer Network) web site are particularly useful for programmers wanting to work with events:</p> + +<ul> + <li>this <a href="/en-US/docs/Web/Guide/API/DOM/Events">Event Guide</a> which is part of the <a href="/en-US/docs/Web/Guide">Web Developers' Guide</a>,</li> + <li>the <a href="/en-US/docs/Web/Reference/Events">Event Reference</a>,</li> + <li>the Web API documentation for the <a href="/en-US/docs/Web/API/Event"><code>Event</code></a> object.</li> +</ul> diff --git a/files/pt-br/web/guide/events/touch_events/index.html b/files/pt-br/web/guide/events/touch_events/index.html new file mode 100644 index 0000000000..df21cdf335 --- /dev/null +++ b/files/pt-br/web/guide/events/touch_events/index.html @@ -0,0 +1,353 @@ +--- +title: Eventos do Toque +slug: Web/Guide/Events/Touch_events +tags: + - Avançado + - DOM + - Evento + - Guía + - Mobile + - Visualização +translation_of: Web/API/Touch_events +--- +<p>Com a finalidade de fornecer suporte de qualidade para interfaces baseadas em toque (touch), os eventos de touch oferecem a capacidade de interpretar a atividade em telas sensíveis ao toque ou trackpads.</p> + +<h2 id="Definições">Definições</h2> + +<dl> + <dt>Surface</dt> + <dd>A superfície sensível ao toque. Pode ser uma tela ou trackpad.</dd> +</dl> + +<dl> + <dt><strong style="font-weight: bold;">T</strong>ouch point</dt> + <dd>Um ponto de contato com a superfície. Pode ser um dedo (ou cotovelo, orelha, nariz, o que seja, mas provavelmente, um dedo) ou uma caneta.</dd> +</dl> + +<h2 id="Interfaces">Interfaces</h2> + +<dl> + <dt>{{ domxref("TouchEvent") }}</dt> + <dd>Representa um evento quando ocorre o estado de toque na superfície.</dd> + <dt>{{ domxref("Touch") }}</dt> + <dd>Representa um único ponto de contato entre o usuário e a superfície sensível a toque.</dd> + <dt>{{ domxref("TouchList") }}</dt> + <dd>Representa um grupo de toques, isto é usado quando usuário tem por exemplo, vários dedos ao mesmo tempo sobre a superfície.</dd> + <dt>{{ domxref("DocumentTouch") }}</dt> + <dd>Contém métodos de conveniência para criar {{ domxref("Touch") }} e objetos {{ domxref("TouchList") }} .</dd> +</dl> + +<h2 id="Exemplo">Exemplo</h2> + +<p>Este exemplo acompanha múltiplos pontos de contato de cada vez, permitindo o usuário desenhe em um {{ HTMLElement("canvas") }} com mais de um dedo por vez. Ele só funcionará em um browser que tenha suporte a eventos de toque.</p> + +<div class="note"><strong>Nota:</strong> O texto a seguir utiliza o termo "finger" quando descreve o contato com a superfície, mas poderia, é claro, ser também uma caneta ou outro método de contato.</div> + +<h3 id="Crie_um_canvas">Crie um canvas</h3> + +<pre class="brush: html"><canvas id="canvas" width="600" height="600" style="border:solid black 1px;"> + Seu browser não tem suporte ao elemento canvas. +</canvas> +<br> +<button onclick="startup()">Initialize</button> +<br> +Log: <pre id="log" style="border: 1px solid #ccc;"></pre> +</pre> + +<h3 id="Configurado_os_eventos">Configurado os eventos</h3> + +<p>Quando uma página é carregada, a função <code>startup()</code> mostrada abaixo deve ser chamada pelo nosso elemento {{ HTMLElement("body") }} através do atributo <code>onload</code> (Mas no exemplo usamos um botão para adicioná-lo, devido as limitações do MDN live example system).</p> + +<pre class="brush: js">function startup() { + var el = document.getElementsByTagName("canvas")[0]; + el.addEventListener("touchstart", handleStart, false); + el.addEventListener("touchend", handleEnd, false); + el.addEventListener("touchcancel", handleCancel, false); + el.addEventListener("touchleave", handleEnd, false); + el.addEventListener("touchmove", handleMove, false); + log("initialized."); +} +</pre> + +<p>Define simplesmento todos os ouvintes dos eventos do nosso elemento {{ HTMLElement("canvas") }} para que possamos trabalhar com os eventos de toque quando eles ocorrerem<span style="line-height: 1.5;">.</span></p> + +<h4 id="Rastreando_novos_toques" style="line-height: 18px;">Rastreando novos toques</h4> + +<p>Vamos acompanhar os toques em seu progresso.</p> + +<pre class="brush: js" style="font-size: 12px;">var ongoingTouches = new Array; </pre> + +<p><span style="line-height: 1.5;">Quando ocorre um evento </span><code style="font-size: 14px;">touchstart</code><span style="line-height: 1.5;">, indicando que um novo toque na superfície tenha ocorrido, a função abaixo </span><code style="font-size: 14px;">handleStart()</code><span style="line-height: 1.5;"> é chamada. </span></p> + +<pre class="brush: js">function handleStart(evt) { + evt.preventDefault(); + log("touchstart."); + var el = document.getElementsByTagName("canvas")[0]; + var ctx = el.getContext("2d"); + var touches = evt.changedTouches; + + for (var i=0; i < touches.length; i++) { + log("touchstart:"+i+"..."); + ongoingTouches.push(copyTouch(touches[i])); + var color = colorForTouch(touches[i]); + ctx.beginPath(); + ctx.arc(touches[i].pageX, touches[i].pageY, 4, 0,2*Math.PI, false); // a circle at the start + ctx.fillStyle = color; + ctx.fill(); + log("touchstart:"+i+"."); + } +} +</pre> + +<p>A chamada {{ domxref("event.preventDefault()") }} mantem o browser a processa o evento de toque ( isso também previne que um mouse event seja despachado). Então, temos o contexto e puxamos a lista de pontos de contato disparados noa propriedade do evento {{ domxref("TouchEvent.changedTouches") }}.</p> + +<p>Depois disso, nós iteramos sobre todos os objetos {{ domxref("Touch") }} da lista e os adicionamos em um array de pontos de contatos ativos e definimos o ponto inicial para desenhar um pequeno circulo; estamos usando um raio de 4 pixels, então um círculo de 4 pixels irá aparecer em nosso canvas.</p> + +<h4 id="Desenhando_movimento_do_toque">Desenhando movimento do toque</h4> + +<p>Cada vez que um ou mais dedos se movem, um evento de TouchMove é disparado, assim chamando nossa função handleMove(). A sua responsabilidade neste exemplo é atualizar as informações armazenadas e desenhar uma linha a partir da posição anterior para a atual de cada toque.</p> + +<pre class="brush: js">function handleMove(evt) { + evt.preventDefault(); + var el = document.getElementsByTagName("canvas")[0]; + var ctx = el.getContext("2d"); + var touches = evt.changedTouches; + + for (var i=0; i < touches.length; i++) { + var color = colorForTouch(touches[i]); + var idx = ongoingTouchIndexById(touches[i].identifier); + + if(idx >= 0) { + log("continuing touch "+idx); + ctx.beginPath(); + log("ctx.moveTo("+ongoingTouches[idx].pageX+", "+ongoingTouches[idx].pageY+");"); + ctx.moveTo(ongoingTouches[idx].pageX, ongoingTouches[idx].pageY); + log("ctx.lineTo("+touches[i].pageX+", "+touches[i].pageY+");"); + ctx.lineTo(touches[i].pageX, touches[i].pageY); + ctx.lineWidth = 4; + ctx.strokeStyle = color; + ctx.stroke(); + + ongoingTouches.splice(idx, 1, copyTouch(touches[i])); // swap in the new touch record + log("."); + } else { + log("can't figure out which touch to continue"); + } + } +} +</pre> + +<p>Esta interação sobre os toques também muda, mas parece em cache as informações em um array para cada toque anterior, a fim de determinar um pont de partida e o destino para o desenho do trajeto. Isto é feito para olhar cada touch da propriedade {{ domxref("Touch.identifier") }}. Esta propriedade é um número inteiro único para cada toque, e mantém-se consistente para cada evento durante o tempo de contato de cada dedo como a superfície.</p> + +<p>Isto permite obter as coordenadas da posição anterior de cada contato e usar os métodos de contexto apropriado para desenhar uma linha que une as duas posições.</p> + +<p>Depois de desenhar a linha, nós chamamos <a href="/en/JavaScript/Reference/Global_Objects/Array/splice" title="en/JavaScript/Reference/Global Objects/Array/splice"><code>Array.splice()</code></a> para substituir as informações previas sobre o ponto de toque com a informação atual no array <code>ongoingTouches</code>.</p> + +<h4 id="Gerenciando_o_final_do_evento_de_toque">Gerenciando o final do evento de toque </h4> + +<p>Quando o usuário retira o dedo da superfície , um evento <code>touchend</code> é disparado. Da mesma forma, se o dedo deslisa para fora do canvas, nós teremos um evento <code>touchleave</code> disparado. Nós tratamos da mesma forma em ambos os casos: chamamos a função <code>handleEnd()</code>. A sua missão é desenhar uma linha para o final do ponto de toque e remover o ponto de toque da lista ongoing.</p> + +<pre class="brush: js">function handleEnd(evt) { + evt.preventDefault(); + log("touchend/touchleave."); + var el = document.getElementsByTagName("canvas")[0]; + var ctx = el.getContext("2d"); + var touches = evt.changedTouches; + + for (var i=0; i < touches.length; i++) { + var color = colorForTouch(touches[i]); + var idx = ongoingTouchIndexById(touches[i].identifier); + + if(idx >= 0) { + ctx.lineWidth = 4; + ctx.fillStyle = color; + ctx.beginPath(); + ctx.moveTo(ongoingTouches[idx].pageX, ongoingTouches[idx].pageY); + ctx.lineTo(touches[i].pageX, touches[i].pageY); + ctx.fillRect(touches[i].pageX-4, touches[i].pageY-4, 8, 8); // and a square at the end + ongoingTouches.splice(idx, 1); // remove it; we're done + } else { + log("can't figure out which touch to end"); + } + } +} +</pre> + +<p>Isto é muito semelhante a função anterior, as únicas diferenças reais são o desenho de um pequeno quadrado para marcar o fim e quando chamamos <a href="/en/JavaScript/Reference/Global_Objects/Array/splice" title="en/JavaScript/Reference/Global Objects/Array/splice"><code style="font-size: 14px;">Array.splice()</code></a>, nós simplesmente removemos a antiga entrada da lista de toque do ongoing, sem adição das informações atualizadas. O resultado é que paramos o tracking do ponto de contato.</p> + +<h4 id="Tratando_toques_cancelados">Tratando toques cancelados</h4> + +<p>Se o dedo do usuário deslisa em uma UI de um navegador, ou o toque de outra forma precisa ser cancelado, o evento touchcancel é disparado e nos chamamaos a função <code>handleCancel()</code>.</p> + +<pre class="brush: js">function handleCancel(evt) { + evt.preventDefault(); + log("touchcancel."); + var touches = evt.changedTouches; + + for (var i=0; i < touches.length; i++) { + ongoingTouches.splice(i, 1); // remove it; we're done + } +} +</pre> + +<p>Uma vez que a idéia dé cancelar imediatamento o toque, nós simplesmente removemos da lista de ongoing sem desenhar uma linha final.</p> + +<h3 id="Funções_de_conveniência">Funções de conveniência</h3> + +<p>Este exemplo usa duas funções de conveniência que deve ser olhado rapidamente para ajudar a fazer o resto do código mais claro</p> + +<h4 id="Selecionando_a_cor_para_cada_toque">Selecionando a cor para cada toque</h4> + +<p>A fim de fazer cada toque desenhar com uma cor diferente, a função <code>colorForTouch()</code> é usada para escolher uma cor com base em um identificador único do toque, Este identificador é um número opaco, mas pelo menos podemos conta com ele diferindo entre os toques ativos no momento.</p> + +<pre class="brush: js">function colorForTouch(touch) { + var r = touch.identifier % 16; + var g = Math.floor(touch.identifier / 3) % 16; + var b = Math.floor(touch.identifier / 7) % 16; + r = r.toString(16); // make it a hex digit + g = g.toString(16); // make it a hex digit + b = b.toString(16); // make it a hex digit + var color = "#" + r + g + b; + log("color for touch with identifier " + touch.identifier + " = " + color); + return color; +} +</pre> + +<p>O resultado desta função é uma string que pode ser usada ao chamar as funções {{ HTMLElement("canvas") }} para setar a cor do desenho. Por exemplo, para um valor {{ domxref("Touch.identifier") }} de 10, o resultado será a string "#aaa".</p> + +<h4 id="Copiando_touch_objects">Copiando touch objects</h4> + +<p>Alguns browsers (mobile Safari, por exemplo) re-usa touch objects entre os eventos, por isso é melhor ter cuidado para copiar os bits, em vez de fazer referência a todo objeto.</p> + +<pre class="brush: js">function copyTouch(touch) { + return { identifier: touch.identifier, pageX: touch.pageX, pageY: touch.pageY }; +}</pre> + +<h4 id="Encontrando_um_toque_ongoing">Encontrando um toque ongoing</h4> + +<p>A função <code>ongoingTouchIndexById()</code> abaixo verifica através do array <code>ongoingTouches</code> para encontrar o toque correspondente ao indentificador passado, então ele retorna o índice do touch no array.</p> + +<pre class="brush: js">function ongoingTouchIndexById(idToFind) { + for (var i=0; i < ongoingTouches.length; i++) { + var id = ongoingTouches[i].identifier; + + if (id == idToFind) { + return i; + } + } + return -1; // não econtrado +} +</pre> + +<h4 id="Mostrando_o_que_está_acontecendo">Mostrando o que está acontecendo</h4> + +<pre class="brush: js">function log(msg) { + var p = document.getElementById('log'); + p.innerHTML = msg + "\n" + p.innerHTML; +}</pre> + +<p>If your browser supports it, you can {{ LiveSampleLink('Example', 'see it live') }}.</p> + +<p><a href="http://jsfiddle.net/Darbicus/z3Xdx/10/" title="http://jsfiddle.net/Darbicus/z3Xdx/10/">jsFiddle example</a></p> + +<h2 id="Additional_tips">Additional tips</h2> + +<p>This section provides additional tips on how to handle touch events in your web application.</p> + +<h3 id="Handling_clicks">Handling clicks</h3> + +<p>Since calling <code>preventDefault()</code> on a <code>touchstart</code> or the first <code>touchmove</code> event of a series prevents the corresponding mouse events from firing, it's common to call <code>preventDefault()</code> on <code>touchmove</code> rather than <code>touchstart</code>. That way, mouse events can still fire and things like links will continue to work. Alternatively, some frameworks have taken to refiring touch events as mouse events for this same purpose. (This example is oversimplified and may result in strange behavior. It is only intended as a guide.)</p> + +<pre class="brush: js">function onTouch(evt) { + evt.preventDefault(); + if (evt.touches.length > 1 || (evt.type == "touchend" && evt.touches.length > 0)) + return; + + var newEvt = document.createEvent("MouseEvents"); + var type = null; + var touch = null; + switch (evt.type) { + case "touchstart": type = "mousedown"; touch = evt.changedTouches[0];break; + case "touchmove": type = "mousemove"; touch = evt.changedTouches[0];break; + case "touchend": type = "mouseup"; touch = evt.changedTouches[0];break; + } + newEvt.initMouseEvent(type, true, true, evt.originalTarget.ownerDocument.defaultView, 0, + touch.screenX, touch.screenY, touch.clientX, touch.clientY, + evt.ctrlKey, evt.altKey, evt.shirtKey, evt.metaKey, 0, null); + evt.originalTarget.dispatchEvent(newEvt); +} +</pre> + +<h3 id="Calling_preventDefault()_only_on_a_second_touch">Calling preventDefault() only on a second touch</h3> + +<p>One technique for preventing things like <code>pinchZoom</code> on a page is to call <code>preventDefault()</code> on the second touch in a series. This behavior is not well defined in the touch events spec, and results in different behavior for different browsers (i.e., iOS will prevent zooming but still allow panning with both fingers; Android will allow zooming but not panning; Opera and Firefox currently prevent all panning and zooming.) Currently, it's not recommended to depend on any particular behavior in this case, but rather to depend on meta viewport to prevent zooming.</p> + +<dl> +</dl> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatChrome("22.0") }}</td> + <td>{{ CompatGeckoDesktop("18.0") }}<br> + Disabled with 24 ({{ bug(888304) }})</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>(Yes)</td> + <td>{{ CompatGeckoMobile("6.0") }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<h3 id="Gecko_notes">Gecko notes</h3> + +<p>The <code>dom.w3c_touch_events.enabled</code> tri-state preference can be used to disable (0), enable (1), and auto-detect(2) support for standard touch events; by default, they're on auto-detect(2). After changing the preference, you must restart the browser for the changes to take effect.</p> + +<div class="note"> +<p>Prior to {{Gecko("12.0")}}, Gecko did not support multi-touch; only one touch at a time was reported.</p> +</div> + +<div class="note"> +<p><strong>Note:</strong> As of {{Gecko("24.0")}}, the touch events support introduced with {{Gecko("18.0")}} has been disabled on the <strong>desktop</strong> version of Firefox, as some popular sites including Google and Twitter are not working properly. Once the bug is fixed, the API will be enabled again. To enable it anyway, open <code>about:config</code> and set the <code>dom.w3c_touch_events.enabled</code> pref to <code>2</code>. The mobile versions including <a href="/en-US/docs/Mozilla/Firefox_for_Android">Firefox for Android</a> and <a href="/en-US/docs/Mozilla/Firefox_OS">Firefox OS</a> are not affected by this change. Also, the API has been enabled on the Metro-style version of Firefox for Windows 8.</p> +</div> + +<div class="note"><strong>Note: </strong>Prior to {{Gecko("6.0") }}, Gecko offered a <a href="/en/DOM/Touch_events_(Mozilla_experimental)" title="en/DOM/Touch events (Mozilla experimental)">proprietary touch event API</a>. That API is now deprecated; you should switch to this one.</div> |