diff options
author | MDN <actions@users.noreply.github.com> | 2021-04-21 00:11:44 +0000 |
---|---|---|
committer | MDN <actions@users.noreply.github.com> | 2021-04-21 00:11:44 +0000 |
commit | de630426a538c1f77d7c59e66827cb75693ed95b (patch) | |
tree | ff14c2d2677ed2137a84d3c322fa2f62e206e63a /files/pt-br/orphaned/web | |
parent | d7a27823444dc11c7ff40ca63a78b3b37ab82837 (diff) | |
download | translated-content-de630426a538c1f77d7c59e66827cb75693ed95b.tar.gz translated-content-de630426a538c1f77d7c59e66827cb75693ed95b.tar.bz2 translated-content-de630426a538c1f77d7c59e66827cb75693ed95b.zip |
[CRON] sync translated content
Diffstat (limited to 'files/pt-br/orphaned/web')
4 files changed, 418 insertions, 0 deletions
diff --git a/files/pt-br/orphaned/web/api/document_object_model/events/index.html b/files/pt-br/orphaned/web/api/document_object_model/events/index.html new file mode 100644 index 0000000000..76e6ec64e1 --- /dev/null +++ b/files/pt-br/orphaned/web/api/document_object_model/events/index.html @@ -0,0 +1,83 @@ +--- +title: Events and the DOM +slug: orphaned/Web/API/Document_Object_Model/Events +translation_of: Web/API/Document_Object_Model/Events +original_slug: Web/API/Document_Object_Model/Events +--- +<div>{{DefaultAPISidebar("DOM")}}</div> + +<h2 id="Introduction" name="Introduction">Introdução</h2> + +<p>Este capítulo descreve o Modelo de Eventos do DOM. A interface de <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-Event" rel="noopener">Eventos</a> é descrita, assim como a interface para registro de eventos em nodes(ou nódulos) no DOM, e <a href="https://wiki.developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener">event listeners</a>, e vários outros exemplos que mostram como diversas interfaces de evento se relacionam uma com a outraThere is an excellent diagram that clearly explains the three phases of event flow through the DOM in the <a href="http://www.w3.org/TR/DOM-Level-3-Events/#dom-event-architecture">DOM Level 3 Events draft</a>.</p> + +<p>Existe um excelente diagrama que explica claramente as três fases do percurso de eventos no DOM em <a href="http://www.w3.org/TR/DOM-Level-3-Events/#dom-event-architecture" rel="noopener">DOM Level 3 Events draft</a>.</p> + +<h2 id="DOM_event_handler_List" name="DOM_event_handler_List">Registrando event listeners</h2> + +<p>Existem 3 formas de registrar uma manipulação de eventos para um elemento DOM.</p> + +<h3 id="EventTarget.addEventListener" name="EventTarget.addEventListener">{{domxref("EventTarget.addEventListener")}}</h3> + +<pre class="brush: js notranslate">// Assuming myButton is a button element +myButton.addEventListener('click', greet, false) +function greet(event){ + // print and have a look at the event object + // always print arguments in case of overlooking any other arguments + console.log('greet:', arguments) + alert('hello world') +} +</pre> + +<p>Este é o método que você deve usar em páginas web modernas.</p> + +<div class="blockIndicator note"> +<p><strong>Nota:</strong> Internet Explorer 6–8 não suportavam este método, oferecendo uma API {{domxref("EventTarget.attachEvent")}} parecida no lugar. Para compatibilidade cross-browser, use uma das muitas bibliotecas JavaScript disponíveis.</p> +</div> + +<p>Mais detalhes podem encontrada na página de referência {{domxref("EventTarget.addEventListener")}}.</p> + +<h3 id="HTML_attribute" name="HTML_attribute"><a href="/en-US/docs/Web/Guide/HTML/Event_attributes">atributo HTML</a></h3> + +<pre class="brush: html notranslate"><button onclick="alert('Hello world!')"> +</pre> + +<p>O código JavaScript no atributo é passado para o objeto Evento através do parâmetro <code>event</code> . <a href="http://dev.w3.org/html5/spec/webappapis.html#the-event-handler-processing-algorithm">O valor return é tratado de uma maneira especial, descrita na especificação HTML.</a></p> + +<div class="blockIndicator warning"> +<p><strong>Cuidado:</strong> Este método deve ser evitado! Ele suja a marcação, e a faz menos legível. Preocupações com o conteúdo/estrutura e comportamento não são bem separadas, tornando mais díficil encontrar um bug.</p> +</div> + +<h3 id="DOM_element_properties" name="DOM_element_properties">DOM element properties</h3> + +<pre class="brush: js notranslate">// Supondo que myButton seja um elemento button +myButton.onclick = function(event){alert('Hello world')} +</pre> + +<p>A função pode ser definida para receber um parâmetro <code>event</code> . <a href="http://dev.w3.org/html5/spec/webappapis.html#the-event-handler-processing-algorithm">O valor return é tratado de maneira especial, descrita na especificação HTML.</a></p> + +<p>O problema deste método é que apenas uma manipulação pode ser definida por elemento e por evento.</p> + +<h2 id="Acessando_interfaces_doEvento">Acessando interfaces doEvento</h2> + +<p>Manipulações do Evento podem ser atribuídas a vários objetos (incluindo elementos DOM, documentos, o {{domxref("window")}} object, etc.). Quando um evento ocorre, o objeto do evento é criado e passado sequencialmente ao event listeners.</p> + +<p>A interface {{domxref("Event")}} é acessível de dentro da função manipuladora, atrás do objeto evento passado como primeiro argumento. O seguinte exemplo simples mostra como um objeto evento é passado á função manipuladora do evento, e pode usado de dentro de tal função.</p> + +<pre class="brush: js notranslate">function print(evt) { + // the evt parameter is automatically assigned the event object + // take care of the differences between console.log & alert + console.log('print:', evt) + alert(evt) +} +// any function should have an appropriate name, that's what called semantic +table_el.onclick = print +</pre> + +<h2 id="Subnav">Subnav</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Document_Object_Model">DOM Reference</a></li> + <li><a href="/en-US/docs/Web/API/Document_Object_Model/Introduction">Introduction to the DOM</a></li> + <li><a href="/en-US/docs/Web/API/Document_Object_Model/Events">Events and the DOM</a></li> + <li><a href="/en-US/docs/Web/API/Document_Object_Model/Examples">Examples</a></li> +</ul> diff --git a/files/pt-br/orphaned/web/guide/events/event_handlers/index.html b/files/pt-br/orphaned/web/guide/events/event_handlers/index.html new file mode 100644 index 0000000000..34fdcb15f8 --- /dev/null +++ b/files/pt-br/orphaned/web/guide/events/event_handlers/index.html @@ -0,0 +1,165 @@ +--- +title: DOM onevent handlers +slug: orphaned/Web/Guide/Events/Event_handlers +translation_of: Web/Guide/Events/Event_handlers +original_slug: 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/orphaned/web/guide/events/index.html b/files/pt-br/orphaned/web/guide/events/index.html new file mode 100644 index 0000000000..d705b4757c --- /dev/null +++ b/files/pt-br/orphaned/web/guide/events/index.html @@ -0,0 +1,37 @@ +--- +title: Event developer guide +slug: orphaned/Web/Guide/Events +tags: + - DOM + - Event + - Guide + - NeedsTranslation + - TopicStub + - events +translation_of: Web/Guide/Events +original_slug: 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/orphaned/web/guide/events/overview_of_events_and_handlers/index.html b/files/pt-br/orphaned/web/guide/events/overview_of_events_and_handlers/index.html new file mode 100644 index 0000000000..950ddd0b4f --- /dev/null +++ b/files/pt-br/orphaned/web/guide/events/overview_of_events_and_handlers/index.html @@ -0,0 +1,133 @@ +--- +title: Uma visão geral sobre Events e Handlers +slug: orphaned/Web/Guide/Events/Overview_of_Events_and_Handlers +translation_of: Web/Guide/Events/Overview_of_Events_and_Handlers +original_slug: 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> |