From de630426a538c1f77d7c59e66827cb75693ed95b Mon Sep 17 00:00:00 2001 From: MDN Date: Wed, 21 Apr 2021 00:11:44 +0000 Subject: [CRON] sync translated content --- files/bn/_redirects.txt | 6 + files/bn/_wikihistory.json | 12 +- files/bn/orphaned/web/guide/events/index.html | 38 +++ files/bn/web/guide/events/index.html | 37 --- files/de/_redirects.txt | 1 + files/de/_wikihistory.json | 14 +- files/de/orphaned/web/guide/events/index.html | 54 ++++ files/de/web/guide/events/index.html | 53 ---- files/es/_redirects.txt | 15 +- files/es/_wikihistory.json | 68 ++--- .../api/detecting_device_orientation/index.html | 279 ++++++++++++++++++ .../api/document_object_model/events/index.html | 73 +++++ .../web/guide/events/event_handlers/index.html | 133 +++++++++ files/es/orphaned/web/guide/events/index.html | 17 ++ .../index.html | 48 ++++ .../api/detecting_device_orientation/index.html | 278 ------------------ .../api/document_object_model/events/index.html | 73 ----- .../es/web/guide/events/event_handlers/index.html | 133 --------- files/es/web/guide/events/index.html | 17 -- .../index.html | 49 ---- files/fi/_redirects.txt | 6 + files/fi/_wikihistory.json | 12 +- files/fi/orphaned/web/guide/events/index.html | 54 ++++ files/fi/web/guide/events/index.html | 53 ---- files/fr/_redirects.txt | 12 +- files/fr/_wikihistory.json | 62 ++-- .../api/detecting_device_orientation/index.html | 220 ++++++++++++++ .../api/document_object_model/events/index.html | 75 +++++ files/fr/orphaned/web/guide/events/index.html | 19 ++ .../index.html | 77 +++++ .../api/detecting_device_orientation/index.html | 220 -------------- .../api/document_object_model/events/index.html | 75 ----- files/fr/web/guide/events/index.html | 19 -- .../index.html | 77 ----- files/ja/_redirects.txt | 14 +- files/ja/_wikihistory.json | 94 +++--- .../api/detecting_device_orientation/index.html | 229 +++++++++++++++ .../api/document_object_model/events/index.html | 89 ++++++ .../web/guide/events/event_handlers/index.html | 173 +++++++++++ files/ja/orphaned/web/guide/events/index.html | 51 ++++ .../index.html | 50 ++++ .../overview_of_events_and_handlers/index.html | 137 +++++++++ .../api/detecting_device_orientation/index.html | 228 --------------- .../api/document_object_model/events/index.html | 88 ------ .../ja/web/guide/events/event_handlers/index.html | 172 ----------- files/ja/web/guide/events/index.html | 50 ---- .../index.html | 49 ---- .../overview_of_events_and_handlers/index.html | 136 --------- files/ko/_redirects.txt | 6 +- files/ko/_wikihistory.json | 52 ++-- .../api/detecting_device_orientation/index.html | 274 ++++++++++++++++++ .../api/document_object_model/events/index.html | 85 ++++++ files/ko/orphaned/web/guide/events/index.html | 52 ++++ .../overview_of_events_and_handlers/index.html | 143 +++++++++ .../api/detecting_device_orientation/index.html | 274 ------------------ .../api/document_object_model/events/index.html | 84 ------ files/ko/web/guide/events/index.html | 51 ---- .../overview_of_events_and_handlers/index.html | 142 --------- files/pt-br/_redirects.txt | 6 +- files/pt-br/_wikihistory.json | 48 ++-- .../api/document_object_model/events/index.html | 83 ++++++ .../web/guide/events/event_handlers/index.html | 165 +++++++++++ files/pt-br/orphaned/web/guide/events/index.html | 37 +++ .../overview_of_events_and_handlers/index.html | 133 +++++++++ .../api/document_object_model/events/index.html | 83 ------ .../web/guide/events/event_handlers/index.html | 164 ----------- files/pt-br/web/guide/events/index.html | 36 --- .../overview_of_events_and_handlers/index.html | 132 --------- files/pt-pt/_redirects.txt | 3 +- files/pt-pt/_wikihistory.json | 12 +- files/pt-pt/orphaned/web/guide/events/index.html | 134 +++++++++ files/pt-pt/web/guide/events/index.html | 134 --------- files/ru/_redirects.txt | 6 +- files/ru/_wikihistory.json | 58 ++-- .../api/document_object_model/events/index.html | 81 ++++++ .../web/guide/events/event_handlers/index.html | 167 +++++++++++ files/ru/orphaned/web/guide/events/index.html | 60 ++++ .../overview_of_events_and_handlers/index.html | 131 +++++++++ .../api/document_object_model/events/index.html | 81 ------ .../ru/web/guide/events/event_handlers/index.html | 166 ----------- files/ru/web/guide/events/index.html | 59 ---- .../overview_of_events_and_handlers/index.html | 130 --------- files/zh-cn/_redirects.txt | 10 +- files/zh-cn/_wikihistory.json | 110 +++---- .../api/detecting_device_orientation/index.html | 319 +++++++++++++++++++++ .../api/document_object_model/events/index.html | 81 ++++++ .../web/guide/events/event_handlers/index.html | 181 ++++++++++++ files/zh-cn/orphaned/web/guide/events/index.html | 55 ++++ .../index.html | 45 +++ .../overview_of_events_and_handlers/index.html | 136 +++++++++ .../api/detecting_device_orientation/index.html | 318 -------------------- .../api/document_object_model/events/index.html | 80 ------ .../web/guide/events/event_handlers/index.html | 180 ------------ files/zh-cn/web/guide/events/index.html | 54 ---- .../index.html | 44 --- .../overview_of_events_and_handlers/index.html | 135 --------- files/zh-tw/_redirects.txt | 8 +- files/zh-tw/_wikihistory.json | 54 ++-- .../api/detecting_device_orientation/index.html | 279 ++++++++++++++++++ .../api/document_object_model/events/index.html | 70 +++++ .../web/guide/events/event_handlers/index.html | 179 ++++++++++++ files/zh-tw/orphaned/web/guide/events/index.html | 53 ++++ .../api/detecting_device_orientation/index.html | 278 ------------------ .../api/document_object_model/events/index.html | 70 ----- .../web/guide/events/event_handlers/index.html | 178 ------------ files/zh-tw/web/guide/events/index.html | 52 ---- 106 files changed, 5129 insertions(+), 5051 deletions(-) create mode 100644 files/bn/orphaned/web/guide/events/index.html delete mode 100644 files/bn/web/guide/events/index.html create mode 100644 files/de/orphaned/web/guide/events/index.html delete mode 100644 files/de/web/guide/events/index.html create mode 100644 files/es/orphaned/web/api/detecting_device_orientation/index.html create mode 100644 files/es/orphaned/web/api/document_object_model/events/index.html create mode 100644 files/es/orphaned/web/guide/events/event_handlers/index.html create mode 100644 files/es/orphaned/web/guide/events/index.html create mode 100644 files/es/orphaned/web/guide/events/orientation_and_motion_data_explained/index.html delete mode 100644 files/es/web/api/detecting_device_orientation/index.html delete mode 100644 files/es/web/api/document_object_model/events/index.html delete mode 100644 files/es/web/guide/events/event_handlers/index.html delete mode 100644 files/es/web/guide/events/index.html delete mode 100644 files/es/web/guide/events/orientation_and_motion_data_explained/index.html create mode 100644 files/fi/orphaned/web/guide/events/index.html delete mode 100644 files/fi/web/guide/events/index.html create mode 100644 files/fr/orphaned/web/api/detecting_device_orientation/index.html create mode 100644 files/fr/orphaned/web/api/document_object_model/events/index.html create mode 100644 files/fr/orphaned/web/guide/events/index.html create mode 100644 files/fr/orphaned/web/guide/events/orientation_and_motion_data_explained/index.html delete mode 100644 files/fr/web/api/detecting_device_orientation/index.html delete mode 100644 files/fr/web/api/document_object_model/events/index.html delete mode 100644 files/fr/web/guide/events/index.html delete mode 100644 files/fr/web/guide/events/orientation_and_motion_data_explained/index.html create mode 100644 files/ja/orphaned/web/api/detecting_device_orientation/index.html create mode 100644 files/ja/orphaned/web/api/document_object_model/events/index.html create mode 100644 files/ja/orphaned/web/guide/events/event_handlers/index.html create mode 100644 files/ja/orphaned/web/guide/events/index.html create mode 100644 files/ja/orphaned/web/guide/events/orientation_and_motion_data_explained/index.html create mode 100644 files/ja/orphaned/web/guide/events/overview_of_events_and_handlers/index.html delete mode 100644 files/ja/web/api/detecting_device_orientation/index.html delete mode 100644 files/ja/web/api/document_object_model/events/index.html delete mode 100644 files/ja/web/guide/events/event_handlers/index.html delete mode 100644 files/ja/web/guide/events/index.html delete mode 100644 files/ja/web/guide/events/orientation_and_motion_data_explained/index.html delete mode 100644 files/ja/web/guide/events/overview_of_events_and_handlers/index.html create mode 100644 files/ko/orphaned/web/api/detecting_device_orientation/index.html create mode 100644 files/ko/orphaned/web/api/document_object_model/events/index.html create mode 100644 files/ko/orphaned/web/guide/events/index.html create mode 100644 files/ko/orphaned/web/guide/events/overview_of_events_and_handlers/index.html delete mode 100644 files/ko/web/api/detecting_device_orientation/index.html delete mode 100644 files/ko/web/api/document_object_model/events/index.html delete mode 100644 files/ko/web/guide/events/index.html delete mode 100644 files/ko/web/guide/events/overview_of_events_and_handlers/index.html create mode 100644 files/pt-br/orphaned/web/api/document_object_model/events/index.html create mode 100644 files/pt-br/orphaned/web/guide/events/event_handlers/index.html create mode 100644 files/pt-br/orphaned/web/guide/events/index.html create mode 100644 files/pt-br/orphaned/web/guide/events/overview_of_events_and_handlers/index.html delete mode 100644 files/pt-br/web/api/document_object_model/events/index.html delete mode 100644 files/pt-br/web/guide/events/event_handlers/index.html delete mode 100644 files/pt-br/web/guide/events/index.html delete mode 100644 files/pt-br/web/guide/events/overview_of_events_and_handlers/index.html create mode 100644 files/pt-pt/orphaned/web/guide/events/index.html delete mode 100644 files/pt-pt/web/guide/events/index.html create mode 100644 files/ru/orphaned/web/api/document_object_model/events/index.html create mode 100644 files/ru/orphaned/web/guide/events/event_handlers/index.html create mode 100644 files/ru/orphaned/web/guide/events/index.html create mode 100644 files/ru/orphaned/web/guide/events/overview_of_events_and_handlers/index.html delete mode 100644 files/ru/web/api/document_object_model/events/index.html delete mode 100644 files/ru/web/guide/events/event_handlers/index.html delete mode 100644 files/ru/web/guide/events/index.html delete mode 100644 files/ru/web/guide/events/overview_of_events_and_handlers/index.html create mode 100644 files/zh-cn/orphaned/web/api/detecting_device_orientation/index.html create mode 100644 files/zh-cn/orphaned/web/api/document_object_model/events/index.html create mode 100644 files/zh-cn/orphaned/web/guide/events/event_handlers/index.html create mode 100644 files/zh-cn/orphaned/web/guide/events/index.html create mode 100644 files/zh-cn/orphaned/web/guide/events/orientation_and_motion_data_explained/index.html create mode 100644 files/zh-cn/orphaned/web/guide/events/overview_of_events_and_handlers/index.html delete mode 100644 files/zh-cn/web/api/detecting_device_orientation/index.html delete mode 100644 files/zh-cn/web/api/document_object_model/events/index.html delete mode 100644 files/zh-cn/web/guide/events/event_handlers/index.html delete mode 100644 files/zh-cn/web/guide/events/index.html delete mode 100644 files/zh-cn/web/guide/events/orientation_and_motion_data_explained/index.html delete mode 100644 files/zh-cn/web/guide/events/overview_of_events_and_handlers/index.html create mode 100644 files/zh-tw/orphaned/web/api/detecting_device_orientation/index.html create mode 100644 files/zh-tw/orphaned/web/api/document_object_model/events/index.html create mode 100644 files/zh-tw/orphaned/web/guide/events/event_handlers/index.html create mode 100644 files/zh-tw/orphaned/web/guide/events/index.html delete mode 100644 files/zh-tw/web/api/detecting_device_orientation/index.html delete mode 100644 files/zh-tw/web/api/document_object_model/events/index.html delete mode 100644 files/zh-tw/web/guide/events/event_handlers/index.html delete mode 100644 files/zh-tw/web/guide/events/index.html diff --git a/files/bn/_redirects.txt b/files/bn/_redirects.txt index 1d401b0273..f9c652b1fd 100644 --- a/files/bn/_redirects.txt +++ b/files/bn/_redirects.txt @@ -1,3 +1,8 @@ +# DO NOT EDIT THIS FILE MANUALLY. +# Use the CLI instead: +# +# yarn content add-redirect +# # FROM-URL TO-URL /bn/docs/DOM /bn/docs/Web/API/Document_Object_Model /bn/docs/HTML/HTML5 /bn/docs/Web/Guide/HTML/HTML5 @@ -30,6 +35,7 @@ /bn/docs/Web/CSS/element /bn/docs/Web/CSS/element() /bn/docs/Web/Guide/API/DOM /bn/docs/conflicting/Web/API/Document_Object_Model /bn/docs/Web/Guide/API/WebRTC /bn/docs/Web/API/WebRTC_API +/bn/docs/Web/Guide/Events /bn/docs/orphaned/Web/Guide/Events /bn/docs/Web/Guide/HTML/Canvas_tutorial /bn/docs/Web/API/Canvas_API/Tutorial /bn/docs/Web/Guide/HTML/Content_Editable /bn/docs/Web/Guide/HTML/Editable_content /bn/docs/Web/Guide/HTML/Forms /bn/docs/Learn/Forms diff --git a/files/bn/_wikihistory.json b/files/bn/_wikihistory.json index 0bdb02ce4d..d48064ffd7 100644 --- a/files/bn/_wikihistory.json +++ b/files/bn/_wikihistory.json @@ -406,12 +406,6 @@ "Sheppy" ] }, - "Web/Guide/Events": { - "modified": "2019-03-23T23:10:51.342Z", - "contributors": [ - "Jeremie" - ] - }, "Web/Guide/Performance": { "modified": "2019-03-23T23:20:59.790Z", "contributors": [ @@ -959,5 +953,11 @@ "contributors": [ "ToufiqAminRumi" ] + }, + "orphaned/Web/Guide/Events": { + "modified": "2019-03-23T23:10:51.342Z", + "contributors": [ + "Jeremie" + ] } } \ No newline at end of file diff --git a/files/bn/orphaned/web/guide/events/index.html b/files/bn/orphaned/web/guide/events/index.html new file mode 100644 index 0000000000..2322c7fdf6 --- /dev/null +++ b/files/bn/orphaned/web/guide/events/index.html @@ -0,0 +1,38 @@ +--- +title: Event developer guide +slug: orphaned/Web/Guide/Events +tags: + - DOM + - Event + - Guide + - NeedsTranslation + - NeedsUpdate + - TopicStub + - events +translation_of: Web/Guide/Events +original_slug: Web/Guide/Events +--- +

{{draft()}}

+

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.

+

The overview page 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.

+

The custom events page 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.

+

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.

+

The device 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 page on orientation coordinate systems and the page on the use of 3D transforms. That is different, but similar, to the change in device vertical orientation. 

+

The window in which the browser is displayed which might trigger events, for example, change size if the user maximizes the window or otherwise changes it.

+

The process 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.

+

The user interaction 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:

+ +

The modification of the web page in structure or content might trigger some events, as is explained in the mutation events page, but the use of these events has been deprecated in favour of the lighter Mutation Observer approach.

+

The media streams embedded in the HTML documents might trigger some events, as explained in the media events page.

+

The network requests made by a web page might trigger some events.

+

There are many other sources of events defined by web browsers for which pages are not yet available in this guide.

+
+

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.

+
+

Docs

+

{{LandingPageListSubpages}}

diff --git a/files/bn/web/guide/events/index.html b/files/bn/web/guide/events/index.html deleted file mode 100644 index 02a20ce36e..0000000000 --- a/files/bn/web/guide/events/index.html +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: Event developer guide -slug: Web/Guide/Events -tags: - - DOM - - Event - - Guide - - NeedsTranslation - - NeedsUpdate - - TopicStub - - events -translation_of: Web/Guide/Events ---- -

{{draft()}}

-

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.

-

The overview page 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.

-

The custom events page 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.

-

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.

-

The device 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 page on orientation coordinate systems and the page on the use of 3D transforms. That is different, but similar, to the change in device vertical orientation. 

-

The window in which the browser is displayed which might trigger events, for example, change size if the user maximizes the window or otherwise changes it.

-

The process 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.

-

The user interaction 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:

- -

The modification of the web page in structure or content might trigger some events, as is explained in the mutation events page, but the use of these events has been deprecated in favour of the lighter Mutation Observer approach.

-

The media streams embedded in the HTML documents might trigger some events, as explained in the media events page.

-

The network requests made by a web page might trigger some events.

-

There are many other sources of events defined by web browsers for which pages are not yet available in this guide.

-
-

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.

-
-

Docs

-

{{LandingPageListSubpages}}

diff --git a/files/de/_redirects.txt b/files/de/_redirects.txt index ce6c7ba2e9..d52340d3f9 100644 --- a/files/de/_redirects.txt +++ b/files/de/_redirects.txt @@ -652,6 +652,7 @@ /de/docs/Web/Guide/CSS/mehrere_Hintergründe_verwenden /de/docs/Web/CSS/CSS_Backgrounds_and_Borders/Using_multiple_backgrounds /de/docs/Web/Guide/DOM /de/docs/conflicting/Web/API/Document_Object_Model_656f0e51418b39c498011268be9b3a10 /de/docs/Web/Guide/DOM/Manipulating_the_browser_history /de/docs/Web/API/History_API +/de/docs/Web/Guide/Events /de/docs/orphaned/Web/Guide/Events /de/docs/Web/Guide/Events/Creating_and_triggering_events /de/docs/orphaned/Web/Guide/Events/Creating_and_triggering_events /de/docs/Web/Guide/HTML /de/docs/Learn/HTML /de/docs/Web/Guide/HTML/Canvas_Tutorial /de/docs/Web/API/Canvas_API/Tutorial diff --git a/files/de/_wikihistory.json b/files/de/_wikihistory.json index 2f6f7a2997..197cc7d25a 100644 --- a/files/de/_wikihistory.json +++ b/files/de/_wikihistory.json @@ -6756,13 +6756,6 @@ "M@d Man" ] }, - "Web/Guide/Events": { - "modified": "2019-03-18T21:10:49.464Z", - "contributors": [ - "stef4412", - "gportioli" - ] - }, "Web/Guide/Graphics": { "modified": "2019-03-23T23:05:58.536Z", "contributors": [ @@ -14837,5 +14830,12 @@ "contributors": [ "td8" ] + }, + "orphaned/Web/Guide/Events": { + "modified": "2019-03-18T21:10:49.464Z", + "contributors": [ + "stef4412", + "gportioli" + ] } } \ No newline at end of file diff --git a/files/de/orphaned/web/guide/events/index.html b/files/de/orphaned/web/guide/events/index.html new file mode 100644 index 0000000000..2f50cfec0c --- /dev/null +++ b/files/de/orphaned/web/guide/events/index.html @@ -0,0 +1,54 @@ +--- +title: Event developer guide +slug: orphaned/Web/Guide/Events +tags: + - DOM + - Event + - Guide + - NeedsTranslation + - NeedsUpdate + - TopicStub + - events +translation_of: Web/Guide/Events +original_slug: Web/Guide/Events +--- +

 

+ +

Events bezieht sich sowohl auf ein Entwurfsmuster, das für die asynchrone Behandlung verschiedener Vorfälle, die während der Lebensdauer einer Webseite auftreten, als auch auf die Benennung, Charakterisierung und Verwendung einer großen Anzahl von Vorfällen unterschiedlicher Art.

+ +

Die Übersichtsseite bietet eine Einführung in das Entwurfsmuster und eine Zusammenfassung der Arten von Vorfällen, die von modernen Webbrowsern definiert werden und darauf reagieren.

+ +

Auf der Seite Benutzerdefinierte Ereignisse wird beschrieben, wie das Ereigniscode-Entwurfsmuster in benutzerdefiniertem Code verwendet werden kann, um neue Ereignistypen zu definieren, die von Benutzerobjekten ausgegeben werden, Listener-Funktionen zum Behandeln dieser Ereignisse zu registrieren und die Ereignisse im Benutzercode auszulösen.

+ +

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.

+ +

The device 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 page on orientation coordinate systems and the page on the use of 3D transforms. That is different, but similar, to the change in device vertical orientation. 

+ +

The window in which the browser is displayed can trigger events; for example, change size if the user maximizes the window or otherwise changes it.

+ +

The process loading of a web page can 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.

+ +

The user interaction with the web page contents can 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:

+ + + +

The modification of the web page in structure or content might trigger some events, as explained in the mutation events page, but the use of these events has been deprecated in favour of the lighter Mutation Observer approach.

+ +

The media streams embedded in the HTML documents might trigger some events, as explained in the media events page.

+ +

The network requests made by a web page might trigger some events.

+ +

There are many other sources of events defined by web browsers for which pages are not yet available in this guide.

+ +
+

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.

+
+ +

Docs

+ +

{{LandingPageListSubpages}}

diff --git a/files/de/web/guide/events/index.html b/files/de/web/guide/events/index.html deleted file mode 100644 index 9fbfac8b89..0000000000 --- a/files/de/web/guide/events/index.html +++ /dev/null @@ -1,53 +0,0 @@ ---- -title: Event developer guide -slug: Web/Guide/Events -tags: - - DOM - - Event - - Guide - - NeedsTranslation - - NeedsUpdate - - TopicStub - - events -translation_of: Web/Guide/Events ---- -

 

- -

Events bezieht sich sowohl auf ein Entwurfsmuster, das für die asynchrone Behandlung verschiedener Vorfälle, die während der Lebensdauer einer Webseite auftreten, als auch auf die Benennung, Charakterisierung und Verwendung einer großen Anzahl von Vorfällen unterschiedlicher Art.

- -

Die Übersichtsseite bietet eine Einführung in das Entwurfsmuster und eine Zusammenfassung der Arten von Vorfällen, die von modernen Webbrowsern definiert werden und darauf reagieren.

- -

Auf der Seite Benutzerdefinierte Ereignisse wird beschrieben, wie das Ereigniscode-Entwurfsmuster in benutzerdefiniertem Code verwendet werden kann, um neue Ereignistypen zu definieren, die von Benutzerobjekten ausgegeben werden, Listener-Funktionen zum Behandeln dieser Ereignisse zu registrieren und die Ereignisse im Benutzercode auszulösen.

- -

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.

- -

The device 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 page on orientation coordinate systems and the page on the use of 3D transforms. That is different, but similar, to the change in device vertical orientation. 

- -

The window in which the browser is displayed can trigger events; for example, change size if the user maximizes the window or otherwise changes it.

- -

The process loading of a web page can 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.

- -

The user interaction with the web page contents can 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:

- - - -

The modification of the web page in structure or content might trigger some events, as explained in the mutation events page, but the use of these events has been deprecated in favour of the lighter Mutation Observer approach.

- -

The media streams embedded in the HTML documents might trigger some events, as explained in the media events page.

- -

The network requests made by a web page might trigger some events.

- -

There are many other sources of events defined by web browsers for which pages are not yet available in this guide.

- -
-

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.

-
- -

Docs

- -

{{LandingPageListSubpages}}

diff --git a/files/es/_redirects.txt b/files/es/_redirects.txt index 4b19728752..073cbf88ad 100644 --- a/files/es/_redirects.txt +++ b/files/es/_redirects.txt @@ -1450,7 +1450,7 @@ /es/docs/Referencia_DOM_de_Gecko /es/docs/Web/API/Document_Object_Model /es/docs/Referencia_DOM_de_Gecko/Cómo_espacioenblanco /es/docs/Web/API/Document_Object_Model/Whitespace /es/docs/Referencia_DOM_de_Gecko/Ejemplos /es/docs/Web/API/Document_Object_Model/Examples -/es/docs/Referencia_DOM_de_Gecko/Eventos /es/docs/Web/API/Document_Object_Model/Events +/es/docs/Referencia_DOM_de_Gecko/Eventos /es/docs/orphaned/Web/API/Document_Object_Model/Events /es/docs/Referencia_DOM_de_Gecko/Introducción /es/docs/Web/API/Document_Object_Model/Introduction /es/docs/Referencia_DOM_de_Gecko/Localizando_elementos_DOM_usando_selectores /es/docs/Web/API/Document_object_model/Locating_DOM_elements_using_selectors /es/docs/Referencia_DOM_de_Gecko/Prefacio /es/docs/conflicting/Web/API/Document_Object_Model_9f3a59543838705de7e9b080fde3cc14 @@ -1791,12 +1791,14 @@ /es/docs/Web/API/Coordinates /es/docs/Web/API/GeolocationCoordinates /es/docs/Web/API/Coordinates/latitude /es/docs/Web/API/GeolocationCoordinates/latitude /es/docs/Web/API/DOMString/Cadenas_binarias /es/docs/Web/API/DOMString/Binary +/es/docs/Web/API/Detecting_device_orientation /es/docs/orphaned/Web/API/Detecting_device_orientation /es/docs/Web/API/Document/abrir /es/docs/Web/API/Document/open /es/docs/Web/API/Document/async /es/docs/Web/API/XMLDocument/async /es/docs/Web/API/Document/crearAtributo /es/docs/Web/API/Document/createAttribute /es/docs/Web/API/DocumentOrShadowRoot/getSelection /es/docs/Web/API/Document/getSelection /es/docs/Web/API/DocumentOrShadowRoot/pointerLockElement /es/docs/Web/API/Document/pointerLockElement /es/docs/Web/API/DocumentOrShadowRoot/styleSheets /es/docs/Web/API/Document/styleSheets +/es/docs/Web/API/Document_Object_Model/Events /es/docs/orphaned/Web/API/Document_Object_Model/Events /es/docs/Web/API/Element/accessKey /es/docs/Web/API/HTMLElement/accessKey /es/docs/Web/API/Element/name /es/docs/conflicting/Web/API /es/docs/Web/API/Element/ongotpointercapture /es/docs/Web/API/GlobalEventHandlers/ongotpointercapture @@ -2039,17 +2041,20 @@ /es/docs/Web/Events/wheel /es/docs/Web/API/Element/wheel_event /es/docs/Web/Guide/AJAX/Comunidad /es/docs/Web/Guide/AJAX/Community /es/docs/Web/Guide/AJAX/Primeros_Pasos /es/docs/Web/Guide/AJAX/Getting_Started -/es/docs/Web/Guide/API/DOM/Events/Orientation_and_motion_data_explained/Orientation_and_motion_data_explained /es/docs/Web/Guide/Events/Orientation_and_motion_data_explained +/es/docs/Web/Guide/API/DOM/Events/Orientation_and_motion_data_explained/Orientation_and_motion_data_explained /es/docs/orphaned/Web/Guide/Events/Orientation_and_motion_data_explained /es/docs/Web/Guide/API/Vibration /es/docs/Web/API/Vibration_API /es/docs/Web/Guide/CSS /es/docs/Learn/CSS /es/docs/Web/Guide/CSS/Cajas_flexibles /es/docs/conflicting/Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox /es/docs/Web/Guide/CSS/probando_media_queries /es/docs/Web/CSS/Media_Queries/Testing_media_queries /es/docs/Web/Guide/DOM /es/docs/conflicting/Web/API/Document_Object_Model_656f0e51418b39c498011268be9b3a10 -/es/docs/Web/Guide/DOM/Events /es/docs/Web/Guide/Events +/es/docs/Web/Guide/DOM/Events /es/docs/orphaned/Web/Guide/Events /es/docs/Web/Guide/DOM/Events/Creacion_y_Activación_Eventos /es/docs/orphaned/Web/Guide/Events/Creating_and_triggering_events -/es/docs/Web/Guide/DOM/Events/Orientation_and_motion_data_explained /es/docs/Web/Guide/Events/Orientation_and_motion_data_explained -/es/docs/Web/Guide/DOM/Events/eventos_controlador /es/docs/Web/Guide/Events/Event_handlers +/es/docs/Web/Guide/DOM/Events/Orientation_and_motion_data_explained /es/docs/orphaned/Web/Guide/Events/Orientation_and_motion_data_explained +/es/docs/Web/Guide/DOM/Events/eventos_controlador /es/docs/orphaned/Web/Guide/Events/Event_handlers +/es/docs/Web/Guide/Events /es/docs/orphaned/Web/Guide/Events /es/docs/Web/Guide/Events/Creating_and_triggering_events /es/docs/orphaned/Web/Guide/Events/Creating_and_triggering_events +/es/docs/Web/Guide/Events/Event_handlers /es/docs/orphaned/Web/Guide/Events/Event_handlers +/es/docs/Web/Guide/Events/Orientation_and_motion_data_explained /es/docs/orphaned/Web/Guide/Events/Orientation_and_motion_data_explained /es/docs/Web/Guide/HTML /es/docs/Learn/HTML /es/docs/Web/Guide/HTML/Canvas_tutorial /es/docs/Web/API/Canvas_API/Tutorial /es/docs/Web/Guide/HTML/Canvas_tutorial/Advanced_animations /es/docs/Web/API/Canvas_API/Tutorial/Advanced_animations diff --git a/files/es/_wikihistory.json b/files/es/_wikihistory.json index 4518fc9495..398ac13f69 100644 --- a/files/es/_wikihistory.json +++ b/files/es/_wikihistory.json @@ -3689,14 +3689,6 @@ "yonatanalexis22" ] }, - "Web/API/Detecting_device_orientation": { - "modified": "2020-08-11T08:30:00.189Z", - "contributors": [ - "juancarlos.rmr", - "rayrojas", - "jairopezlo" - ] - }, "Web/API/DeviceMotionEvent": { "modified": "2020-10-15T22:22:26.832Z", "contributors": [ @@ -15147,12 +15139,6 @@ "Nathymig" ] }, - "Web/API/Document_Object_Model/Events": { - "modified": "2019-03-18T21:45:13.362Z", - "contributors": [ - "recortes" - ] - }, "Web/API/Document_Object_Model": { "modified": "2019-01-16T16:01:11.054Z", "contributors": [ @@ -16476,13 +16462,6 @@ "Seres" ] }, - "Web/Guide/Events/Orientation_and_motion_data_explained": { - "modified": "2019-03-23T23:27:10.499Z", - "contributors": [ - "Sheppy", - "rubencidlara" - ] - }, "Web/API/Vibration_API": { "modified": "2019-03-23T23:03:32.169Z", "contributors": [ @@ -16495,19 +16474,6 @@ "TibicenasDesign" ] }, - "Web/Guide/Events/Event_handlers": { - "modified": "2020-08-01T23:47:25.815Z", - "contributors": [ - "Enesimus", - "alesalva" - ] - }, - "Web/Guide/Events": { - "modified": "2019-03-23T23:27:18.635Z", - "contributors": [ - "Sheppy" - ] - }, "Web/API/Canvas_API/Tutorial/Advanced_animations": { "modified": "2019-03-23T22:11:01.831Z", "contributors": [ @@ -23743,5 +23709,39 @@ "enreda", "Soid" ] + }, + "orphaned/Web/API/Detecting_device_orientation": { + "modified": "2020-08-11T08:30:00.189Z", + "contributors": [ + "juancarlos.rmr", + "rayrojas", + "jairopezlo" + ] + }, + "orphaned/Web/API/Document_Object_Model/Events": { + "modified": "2019-03-18T21:45:13.362Z", + "contributors": [ + "recortes" + ] + }, + "orphaned/Web/Guide/Events/Event_handlers": { + "modified": "2020-08-01T23:47:25.815Z", + "contributors": [ + "Enesimus", + "alesalva" + ] + }, + "orphaned/Web/Guide/Events": { + "modified": "2019-03-23T23:27:18.635Z", + "contributors": [ + "Sheppy" + ] + }, + "orphaned/Web/Guide/Events/Orientation_and_motion_data_explained": { + "modified": "2019-03-23T23:27:10.499Z", + "contributors": [ + "Sheppy", + "rubencidlara" + ] } } \ No newline at end of file diff --git a/files/es/orphaned/web/api/detecting_device_orientation/index.html b/files/es/orphaned/web/api/detecting_device_orientation/index.html new file mode 100644 index 0000000000..96afd861e0 --- /dev/null +++ b/files/es/orphaned/web/api/detecting_device_orientation/index.html @@ -0,0 +1,279 @@ +--- +title: Detectando la orientación del dispositivo +slug: orphaned/Web/API/Detecting_device_orientation +translation_of: Web/API/Detecting_device_orientation +original_slug: Web/API/Detecting_device_orientation +--- +
{{SeeCompatTable}}
+ +

Resumen

+ +

Cada vez más, los dispositivos habilitados para la web son capaces de determinar su orientación; esto hace que estos puedan reportar datos indicando los cambios de su orientación con relación a la fuerza de gravedad. In particular, dispositivos de mano como los teléfonos móviles pueden usar esta información para rotar la pantalla automaticamente para mostrar información en de forma vertical, presentando un vista extendida del contenido de la web cuando el dispositivo de forma que el ancho es mayor que el alto. 

+ +

Hay dos eventos JavaScript que manejan la información de orientación. El primero es {{domxref("DeviceOrientationEvent")}}, que es enviado cuando el aceleromentro detecta un cambio de orientación del dispositivo. Recibiendo y procesando los datos reportados por el evento es posible responder interactivamente a la rotación y aplicar cambios correspondientes al movimiento del dispositivo.

+ +

El segundo evento es {{domxref("DeviceMotionEvent")}}, que es enviado cuando un cambio de la aceleración fue añadido. Esto es diferente de {{domxref("DeviceOrientationEvent")}} por que está escuchando cambios de aceleración mas no de orientación. Los sensores son comunmente capaces de detetar {{domxref("DeviceMotionEvent")}} incluso aquellos sensores de laptops que protegen del movimiento a los disposivitos de almacenamiento. {{domxref("DeviceOrientationEvent")}} es comunmente encontrado en dispositivos móviles.

+ +

Trabajando con eventos de orientación

+ +

Todo lo que necesitas hacer para empezar a recibir cambios de orientación es escuchar el evento {{ event("deviceorientation") }}:

+ +
window.addEventListener("deviceorientation", handleOrientation, true);
+
+ +

Después de registrar el evento de escucha (en este caso, una función de JavaScript llamada handleOrientation()), tu función de escucha periodicamente será invocada con una actualización de datos.

+ +

La información del evento contiene 4 valores:

+ +
    +
  • {{ domxref("DeviceOrientationEvent.absolute") }}
  • +
  • {{ domxref("DeviceOrientationEvent.alpha") }}
  • +
  • {{ domxref("DeviceOrientationEvent.beta") }}
  • +
  • {{ domxref("DeviceOrientationEvent.gamma") }}
  • +
+ +

El manejador del evento puede ser similar a lo siguiente:

+ +
function handleOrientation(event) {
+  var absolute = event.absolute;
+  var alpha    = event.alpha;
+  var beta     = event.beta;
+  var gamma    = event.gamma;
+
+  // Do stuff with the new orientation data
+}
+
+ +

Explicación de los Valores de Orientación

+ +

El valor reportado para cada eje indica la cantidad de rotación alrededor de un eje dado, con referencia a un estandar marco de coordenadas. El siguiente enlace describe con mayor detalle la Orientacíon y datos del movimiento explicado que es resumido abajo. 

+ +
    +
  • {{ domxref("DeviceOrientationEvent.alpha") }} representa el movimiento alrededor del eje z, representado en grados con valores que van desde 0 a 360.
  • +
  • {{ domxref("DeviceOrientationEvent.beta") }} representa el movimiento del dispositivo alrededor del eje x, representado en grados con valores que van desde -180 a 180.  Esto representa un movimiento de frente hacia atrás del dispositivo.
  • +
  • {{ domxref("DeviceOrientationEvent.gamma") }} representa el movimiento del dispositivo alrededor del eje y, representado en grados con valores que van de -90 a 90. Esto representa un movimiento de izquierda a derecha del dispositivo.
  • +
+ +

Ejemplo de orientación

+ +

Este ejemplo va a funcionar en cualquier nevegador que soporte el evento {{event("deviceorientation")}} y funcione en un dispositivo con capacidades de detectar la orientación.

+ +

Imaginemos una pelota en un jardin:

+ +
<div class="garden">
+  <div class="ball"></div>
+</div>
+
+<pre class="output"></pre>
+
+ +

Este jardin tiene 200 pixeles de ancho (Si, es uno pequeño), y la pelota esta en el centro:

+ +
.garden {
+  position: relative;
+  width : 200px;
+  height: 200px;
+  border: 5px solid #CCC;
+  border-radius: 10px;
+}
+
+.ball {
+  position: absolute;
+  top   : 90px;
+  left  : 90px;
+  width : 20px;
+  height: 20px;
+  background: green;
+  border-radius: 100%;
+}
+
+ +

Ahora, si nosotros movemos nuestro dispositivo, la pelota va a moverse acorde a este:

+ +
var ball   = document.querySelector('.ball');
+var garden = document.querySelector('.garden');
+var output = document.querySelector('.output');
+
+var maxX = garden.clientWidth  - ball.clientWidth;
+var maxY = garden.clientHeight - ball.clientHeight;
+
+function handleOrientation(event) {
+  var x = event.beta;  // In degree in the range [-180,180]
+  var y = event.gamma; // In degree in the range [-90,90]
+
+  output.innerHTML  = "beta : " + x + "\n";
+  output.innerHTML += "gamma: " + y + "\n";
+
+  // Because we don't want to have the device upside down
+  // We constrain the x value to the range [-90,90]
+  if (x >  90) { x =  90};
+  if (x < -90) { x = -90};
+
+  // To make computation easier we shift the range of
+  // x and y to [0,180]
+  x += 90;
+  y += 90;
+
+  // 10 is half the size of the ball
+  // It center the positioning point to the center of the ball
+  ball.style.top  = (maxX*x/180 - 10) + "px";
+  ball.style.left = (maxY*y/180 - 10) + "px";
+}
+
+window.addEventListener('deviceorientation', handleOrientation);
+
+ +

Aqui el resultado en vivo:

+ +
{{ EmbedLiveSample('Orientation_example', '230', '260') }}
+ +
+

Tener en cuenta: Chrome y Firefox no manejan los angulos de la misma forma, asi que en algunos ejes la dirección se invierte.

+
+ +

Procesando eventos de movimiento

+ +

Eventos de movimiento son manejados de la misma manera que la orientación, con la excepción de que estos tienen sus propios nombres de evento: {{ event("devicemotion") }}

+ +
window.addEventListener("devicemotion", handleMotion, true);
+ +

Lo que realmente ha cambiado es la información proporcionada en {{ domxref("DeviceMotionEvent") }} objeto pasado como parametro de la función HandleMotion.

+ +

El evento de movimiento tiene cuatro propiedades:

+ +
    +
  • {{ domxref("DeviceMotionEvent.acceleration") }}
  • +
  • {{ domxref("DeviceMotionEvent.accelerationIncludingGravity") }}
  • +
  • {{ domxref("DeviceMotionEvent.rotationRate") }}
  • +
  • {{ domxref("DeviceMotionEvent.interval") }}
  • +
+ +

Valores de movimiento explicados

+ +

{{ domxref("DeviceMotionEvent") }} proporciona a los desarrolladores web información sobre la velocidad de los cambios de la posición y orientación del dispositivo. Los cambios son proporcionados por sus tres ejes (ver Datos de orientación y movimiento explicados por más detalles).

+ +

Para {{domxref("DeviceMotionEvent.acceleration","acceleration")}} y {{domxref("DeviceMotionEvent.accelerationIncludingGravity","accelerationIncludingGravity")}}, los ejes corresponden a lo siguiente:

+ +
    +
  • x: Representa el eje de oeste a este.
  • +
  • y: Representa el eje de sur a norte.
  • +
  • z: Representa el eje perpendicular al suelo.
  • +
+ +

Para {{domxref("DeviceMotionEvent.rotationRate","rotationRate")}}, la situación es un poco diferente; la información corresponde a lo siguiente en cada caso:

+ +
    +
  • alpha: Representa la velocidad de rotación a lo largo del eje perpendicular a la pantalla ( teclado para desktop).
  • +
  • beta: Representa la velocidad de rotación  a lo largo del eje que va de la izquierda a la derecha del plano de la pantalla (o teclado para desktop).
  • +
  • gamma: Representa la velocidad de rotación  a lo largo del eje que va desde la parte inferior a la parte superrior del plano de la pantalla (o teclado para desktop).
  • +
+ +

Finalmente, {{domxref("DeviceMotionEvent.interval","interval")}} representa el intervalo de tiempo, en milisegundos, en el que los datos han sido obtenidos del dispositivo.

+ +

Especificaciones

+ + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('Device Orientation')}}{{Spec2('Device Orientation')}}Especificación inicial.
+ +

Compatibilidad con navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
{{domxref("DeviceOrientationEvent")}}7.03.6[1]
+ 6
{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
{{domxref("DeviceMotionEvent")}}{{ CompatVersionUnknown() }}6{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
{{domxref("DeviceOrientationEvent")}}3.03.6[1]
+ 6
{{ CompatNo() }}{{ CompatNo() }}4.2
{{domxref("DeviceMotionEvent")}}{{ CompatVersionUnknown() }}6{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+

Note: gyronorm.js es un polyfill para normalizar los datos del acelerómetro y giroscopio en dispositivos móviles. Esto es útil para superar algunas de las diferencias en la compatibilidad del dispositivo con la orientación del dispositivo..

+
+ +

Gecko implementation notes

+ +
    +
  1. Firefox 3.6, 4, and 5 supported mozOrientation versus the standard {{domxref("DeviceOrientationEvent")}} event
  2. +
+ +

Vea también

+ + diff --git a/files/es/orphaned/web/api/document_object_model/events/index.html b/files/es/orphaned/web/api/document_object_model/events/index.html new file mode 100644 index 0000000000..b40c7ce7ae --- /dev/null +++ b/files/es/orphaned/web/api/document_object_model/events/index.html @@ -0,0 +1,73 @@ +--- +title: Eventos y el DOM +slug: orphaned/Web/API/Document_Object_Model/Events +tags: + - DOM + - Guía +translation_of: Web/API/Document_Object_Model/Events +original_slug: Web/API/Document_Object_Model/Events +--- +

Introducción

+ +

Este capítulo describe el Modelo de Eventos del DOM. Se describe la interfaz Event, así como las interfaces para el registro de eventos en los nodos del DOM, y los oyentes de eventos, y varios ejemplos más largos muestran cómo se relacionan entre sí las diversas interfaces de eventos.

+ +

Hay un diagrama excelente que explica claramente las tres fases del flujo de eventos a través del DOM en el borrador DOM Level 3 Events.

+ +

Vea también el Ejemplo 5: Propagación de eventos en el capítulo de Ejemplos para un ejemplo más detallado de cómo los eventos se mueven a través del DOM.

+ +

Registrando oyentes de eventos

+ +

Hay 3 formas de registrar gestores de eventos para un elemento DOM.

+ +

EventTarget.addEventListener

+ +
// Se supone que myButton es un elemento de botón
+myButton.addEventListener('click', function(){alert('Hello world');}, false);
+
+ +

Este es el método que debe usar en las páginas web modernas. 

+ +

Nota: Internet Explorer 6-8 no admite este método, ofreciendo una API similar {{domxref("EventTarget.attachEvent")}} en su lugar. Para la compatibilidad entre navegadores utilice una de las muchas bibliotecas de JavaScript disponibles.

+ +

Se pueden encontrar más detalles en la página de referencia {{domxref("EventTarget.addEventListener")}}.

+ +

Atributo HTML

+ +
<button onclick="alert('Hello world!')">
+
+ +

El código de JavaScript en el atributo pasa el objeto Event por medio del parámetro event. El valor de retorno se trata de una manera especial, descrita en la especificación HTML.

+ +

Debe evitarse esta forma. Hace que el marcado sea más grande y menos legible. El comitido del contenido/estructura y del comportamiento no están bien separadas, por lo que es más difícil encontrar un error.

+ +

Propiedades del elemento DOM

+ +
// Se supone que myButton es un elemento de botón
+myButton.onclick = function(event){alert('Hello world');};
+
+ +

La función se puede defirnir para que tome un parámetro event. El valor de retorno se trata de una manera especial, descrita en la especificación HTML.

+ +

El problema con este método es que solo se puede establecer un gestor por elemento y por evento.

+ +

Accediendo a las Interfaces de eventos

+ +

Los controladores de eventos se pueden adjuntar a varios objetos, incluidos los elementos DOM, documentos, al objeto window, etc. Cuando se produce un evento, se crea un objeto de evento y se pasa secuencialmente a los oyentes del evento.

+ +

Se puede acceder a la interfaz {{domxref ("Evento")}} desde la función del gestor, a través del objeto de evento pasado como primer argumento. El siguiente ejemplo simple muestra cómo se pasa un objeto de evento a la función del controlador de eventos, y se puede usar desde dentro de una de esas funciones.

+ +
function foo(evt) {
+  // al parámetro evt se le asigna automáticamente el objeto event
+  alert(evt);
+}
+table_el.onclick = foo;
+
+ + + + diff --git a/files/es/orphaned/web/guide/events/event_handlers/index.html b/files/es/orphaned/web/guide/events/event_handlers/index.html new file mode 100644 index 0000000000..1c298b7826 --- /dev/null +++ b/files/es/orphaned/web/guide/events/event_handlers/index.html @@ -0,0 +1,133 @@ +--- +title: Manejadores de eventos en el DOM +slug: orphaned/Web/Guide/Events/Event_handlers +translation_of: Web/Guide/Events/Event_handlers +original_slug: Web/Guide/Events/Event_handlers +--- +

La plataforma Web provee varias formas de recibir notificaciones de los eventos del DOM.  Dos de las formas más comunes son: la general {{domxref("EventTarget.addEventListener", "addEventListener()")}} y un conjunto específico de controladores de eventos específicos. Esta página se enfoca en los detalles de cómo funcionan estos.

+ +

Registering on-event handlers

+ +

Los controladores on-event son un grupo de propiedades ofrecidas por los elementos del DOM para ayudar a manejar cómo los elementos reaccionan a los eventos. Los elementos pueden ser interactivos (por ejemplo: enlaces, botones, imagenes, formularios) or non-interactive (e.g. the base document). Los eventos pueden ser cuando se haga un click, detectar cuando se presione una tecla,  enfocarse, entre otros. Los handlers on-event son comunmente denominados como el evento al cual deben reaccionar, como ser onclick, onkeypress, onfocus, etc.

+ +

Pueden especificar un controlador de evento on<...> para un evento en particular (como {{event("click")}}) como un opbjeto determinado de diferentes formas:

+ +
    +
  • Usando el HTML {{Glossary("atributo")}} llamados on{eventtype} en un elemento, por ejemplo:
    + <button onclick="return handleClick(event);">,
  • +
  • O seteandolo {{Glossary("property/JavaScript", "property")}} desde JavaScript, por ejemplo:
    + document.getElementById("mybutton").onclick = function(event) { ... }.
  • +
+ +

Un controlador onevent

+ +

Notese que cada objeto puede tener sólo un controlador on-event para un evento dado (though that handler could call multiple sub-handlers). This is why {{domxref("EventTarget.addEventListener", "addEventListener()")}} is often the better way to get notified of events, especially when wishing to apply various event handlers independently from each other, even for the same event and/or to the same element.

+ +

Also note that on-event handlers are called automatically, not at the programmer's will (although you can, like  mybutton.onclick(myevent); ) since they serve more as placeholders to which a real handler function can be assigned.

+ +

Non-element objects

+ +

Event handlers can also be set using properties on many non-element objects that generate events, including {{ domxref("window") }}, {{ domxref("document") }}, {{ domxref("XMLHttpRequest") }}, and others, for example:

+ +
xhr.onprogress = function() { ... }
+ +

Details

+ +

The value of HTML on<...> attributes and corresponding  JavaScript properties

+ +

A handler registered via an on<...> attribute will be available via the corresponding on<...> property, but not the other way around:

+ +
<div id="a" onclick="alert('old')">Open the Developer Tools Console to see the output.</div>
+
+<script>
+window.onload = function () {
+  var div = document.getElementById("a");
+  console.log("Attribute reflected as a property: ", div.onclick.toString());
+  // Prints: function onclick(event) { alert('old') }
+  div.onclick = function() { alert('new') };
+  console.log("Changed property to: ", div.onclick.toString());
+  // Prints: function () { alert('new') }
+  console.log("Attribute value is unchanged: ", div.getAttribute("onclick"));
+  // Prints: alert('old')
+}
+</script>
+ +

For historical reasons, some attributes/properties on the {{HTMLElement("body")}} and {{HTMLElement("frameset")}} elements actually set event handlers on their parent {{domxref("Window")}} object. (The HTML specification names these: onblur, onerror, onfocus, onload, onscroll.)

+ +

Event handler's parameters, this binding, and the return value

+ +

When the event handler is specified as an HTML attribute, the specified code is wrapped into a function with the following parameters:

+ +
    +
  • event - for all event handlers, except {{domxref("GlobalEventHandlers.onerror", "onerror")}}.
  • +
  • event, source, lineno, colno, and error for the {{domxref("GlobalEventHandlers.onerror", "onerror")}} event handler. Note that the event parameter actually contains the error message as string.
  • +
+ +

When the event handler is invoked, the this keyword inside the handler is set to the DOM element on which the handler is registered. For more details see the this keyword documentation.

+ +

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 "The event handler processing algorithm" in the HTML specification.

+ +

When the event handler is invoked

+ +

TBD (non-capturing listener)

+ +

Terminology

+ +

The term event handler may be used to refer to:

+ +
    +
  • any function or object registered to be notified of events,
  • +
  • or, more specifically, to the mechanism of registering event listeners via on... attributes in HTML or properties in web APIs, such as <button onclick="alert(this)"> or window.onload = function() { /* ... */ }.
  • +
+ +

When discussing the various methods of listening to events,

+ +
    +
  • event listener refers to a function or object registered via {{domxref("EventTarget.addEventListener()")}},
  • +
  • whereas event handler refers to a function registered via on... attributes or properties.
  • +
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML5 W3C')}}
+ +

Browser compatibility

+ +

Event handler changes in Firefox 9

+ +

In order to better match the specifications, and improve cross-browser compatibility, the way event handlers were implemented at a fundamental level changed in Gecko 9.0 {{ geckoRelease("9.0") }}.

+ +

Specifically, in the past, event handlers were not correctly implemented as standard IDL attributes. In Gecko 9.0, this was changed. Because of this, certain behaviors of event handlers in Gecko have changed. In particular, they now behave in all the ways standard IDL attributes behave. In most cases, this shouldn't affect web or add-on content at all; however, there are a few specific things to watch out for.

+ +

Detecting the presence of event handler properties

+ +

You can now detect the presence of an event handler property (that is, for example, onload), using the JavaScript in operator. For example:

+ +
if ("onsomenewfeature" in window) {
+  /* do something amazing */
+}
+
+ +

Event handlers and prototypes

+ +

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 Window.prototype.onload anymore. In the past, event handlers (onload, 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.

diff --git a/files/es/orphaned/web/guide/events/index.html b/files/es/orphaned/web/guide/events/index.html new file mode 100644 index 0000000000..f9469eba26 --- /dev/null +++ b/files/es/orphaned/web/guide/events/index.html @@ -0,0 +1,17 @@ +--- +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 +--- +

{{draft()}}

+

Everything you need to know about events will go under here. We're working on cleanup here now.

+

Docs

+

{{LandingPageListSubpages}}

diff --git a/files/es/orphaned/web/guide/events/orientation_and_motion_data_explained/index.html b/files/es/orphaned/web/guide/events/orientation_and_motion_data_explained/index.html new file mode 100644 index 0000000000..d6e7708621 --- /dev/null +++ b/files/es/orphaned/web/guide/events/orientation_and_motion_data_explained/index.html @@ -0,0 +1,48 @@ +--- +title: Explicación de los datos de orientación y movimiento +slug: orphaned/Web/Guide/Events/Orientation_and_motion_data_explained +translation_of: Web/Guide/Events/Orientation_and_motion_data_explained +original_slug: Web/Guide/Events/Orientation_and_motion_data_explained +--- +

{{ Draft() }}

+

Sumario

+

Cuando se utiliza la orientación y los eventos de movimiento, es importante entender cuáles son los significados de los valores en el navegador. En este artículo se proporciona información acerca de los sistemas de coordenadas en el juego y la forma de usarlos.

+
+

Atención: Actualmente, Firefox y Chrome no soporta la orientación de la misma forma. Ten cuidado con esto cuando sea imprementado en un navegador u otro.

+
+

Acerca de los marcos de coordenadas

+

Un marco de coordenadas en un sistema en el que la orientacion de los tres ejers (X, Y y Z) se definen en referencia a un objeto. Hay dos marcos de coordenadas a considerar cuando se utiliza eventos de orientación y el movimiento:

+

Marco de coordenadas terrestres

+

El marco de coordenadas de terrestres es el sistema de coordenadas fijado en el centro de la Tierra, es decir, los ejes están alineados sobre la base de la fuerza de la gravedad y la orientación norte magnético estándar. Utilizamos las letras mayúsculas ("X", "Y" y "Z") para describir los ejes del sistema de coordenadas terrestre.

+
    +
  • El eje X sigue a lo largo (profuncidad) del plano de tierra, perpendicular al eje Y y positiva hacia el este (y por lo tanto negativa hacia el oeste).
  • +
  • El eje Y sigue a lo largo(ancho) del plano de tierra, y es positivo hacia el norte verdadero (es decir, el Polo Norte, el norte no es magnético) y negativo hacia la verdadera sur.
  • +
  • El eje Z es perpendicular al plano de tierra, piensa en él como una línea trazada entre el dispositivo y el centro de la Tierra. El valor de la coordenada Z es positivo hacia arriba (distancia desde el centro de la Tierra) y negativo hacia abajo (hacia el centro de la Tierra).
  • +
+

 

+

+

 

+

Marco de coordenadas del dispositivo

+

El marco de coordenadas del dispositivo es el marco de la coordinación fijada en el centro del dispositivo. Utilizamos letras minúsculas ("x", "y" y "z") para describir los ejes de las coordenadas del del dispositivo

+

axes.png

+
    +
  • El eje x está en el plano de la pantalla y es positiva hacia la derecha y negativa hacia la izquierda.
  • +
  • El eje y está en el plano de la pantalla y es positiva hacia la parte superior y negativa hacia la parte inferior.
  • +
  • El eje z es perpendicular a la pantalla o teclado, y es positivo que se extiende hacia fuera de la pantalla.
  • +
+
+ Nota: En un teléfono o tableta, la orientación del dispositivo siempre se considera en relación con la orientación estándar de la pantalla, lo que es la orientación "retrato" en la mayoría de los dispositivos. En una computadora portátil, la orientación se considera en relación con el teclado. Si desea detectar cambios en la orientación del dispositivo con el fin de compensar, se puede utilizar el evento orientationChange.
+

Sobre la rotación

+

La rotación se describe alrededor de cualquier eje dado en términos del número de grados de diferencia entre el marco de coordenadas del dispositivo y el marco de coordenadas de la Tierra, y se mide en grados.

+

Alpha

+

Rotación alrededor del eje z - es decir, girando el dispositivo - hace que el ángulo de rotación alfa cambie:

+

alpha.png

+

El ángulo alfa es de 0 °, cuando la parte superior del dispositivo se apunta directamente hacia el polo norte de la Tierra, y aumenta a medida que el dispositivo se gira hacia la izquierda.

+

Beta

+

Rotación alrededor del eje X - es decir, inclinando el dispositivo desde o hacia el usuario - hace que el ángulo de giro beta cambie:

+

beta.png

+

El ángulo beta es de 0 ° en la parte superior e inferior del dispositivo son la misma distancia de la superficie de la Tierra, y aumenta hacia 180 ° como el dispositivo se inclina hacia adelante y disminuye hacia -180 ° como el dispositivo se inclina hacia atrás.

+

Gamma

+

Rotación alrededor del eje Y - es decir, la inclinación del dispositivo hacia la izquierda o hacia la derecha - hace que el ángulo de giro gamma cambie:

+

gamma.png

+

El ángulo gamma es 0 °, cuando los lados izquierdo y derecho del dispositivo son la misma distancia de la superficie de la Tierra, y aumenta hacia 90 ° como el dispositivo se inclina hacia la derecha, y hacia -90 ° como el dispositivo se inclina hacia el izquierda.

diff --git a/files/es/web/api/detecting_device_orientation/index.html b/files/es/web/api/detecting_device_orientation/index.html deleted file mode 100644 index 60302ae643..0000000000 --- a/files/es/web/api/detecting_device_orientation/index.html +++ /dev/null @@ -1,278 +0,0 @@ ---- -title: Detectando la orientación del dispositivo -slug: Web/API/Detecting_device_orientation -translation_of: Web/API/Detecting_device_orientation ---- -
{{SeeCompatTable}}
- -

Resumen

- -

Cada vez más, los dispositivos habilitados para la web son capaces de determinar su orientación; esto hace que estos puedan reportar datos indicando los cambios de su orientación con relación a la fuerza de gravedad. In particular, dispositivos de mano como los teléfonos móviles pueden usar esta información para rotar la pantalla automaticamente para mostrar información en de forma vertical, presentando un vista extendida del contenido de la web cuando el dispositivo de forma que el ancho es mayor que el alto. 

- -

Hay dos eventos JavaScript que manejan la información de orientación. El primero es {{domxref("DeviceOrientationEvent")}}, que es enviado cuando el aceleromentro detecta un cambio de orientación del dispositivo. Recibiendo y procesando los datos reportados por el evento es posible responder interactivamente a la rotación y aplicar cambios correspondientes al movimiento del dispositivo.

- -

El segundo evento es {{domxref("DeviceMotionEvent")}}, que es enviado cuando un cambio de la aceleración fue añadido. Esto es diferente de {{domxref("DeviceOrientationEvent")}} por que está escuchando cambios de aceleración mas no de orientación. Los sensores son comunmente capaces de detetar {{domxref("DeviceMotionEvent")}} incluso aquellos sensores de laptops que protegen del movimiento a los disposivitos de almacenamiento. {{domxref("DeviceOrientationEvent")}} es comunmente encontrado en dispositivos móviles.

- -

Trabajando con eventos de orientación

- -

Todo lo que necesitas hacer para empezar a recibir cambios de orientación es escuchar el evento {{ event("deviceorientation") }}:

- -
window.addEventListener("deviceorientation", handleOrientation, true);
-
- -

Después de registrar el evento de escucha (en este caso, una función de JavaScript llamada handleOrientation()), tu función de escucha periodicamente será invocada con una actualización de datos.

- -

La información del evento contiene 4 valores:

- -
    -
  • {{ domxref("DeviceOrientationEvent.absolute") }}
  • -
  • {{ domxref("DeviceOrientationEvent.alpha") }}
  • -
  • {{ domxref("DeviceOrientationEvent.beta") }}
  • -
  • {{ domxref("DeviceOrientationEvent.gamma") }}
  • -
- -

El manejador del evento puede ser similar a lo siguiente:

- -
function handleOrientation(event) {
-  var absolute = event.absolute;
-  var alpha    = event.alpha;
-  var beta     = event.beta;
-  var gamma    = event.gamma;
-
-  // Do stuff with the new orientation data
-}
-
- -

Explicación de los Valores de Orientación

- -

El valor reportado para cada eje indica la cantidad de rotación alrededor de un eje dado, con referencia a un estandar marco de coordenadas. El siguiente enlace describe con mayor detalle la Orientacíon y datos del movimiento explicado que es resumido abajo. 

- -
    -
  • {{ domxref("DeviceOrientationEvent.alpha") }} representa el movimiento alrededor del eje z, representado en grados con valores que van desde 0 a 360.
  • -
  • {{ domxref("DeviceOrientationEvent.beta") }} representa el movimiento del dispositivo alrededor del eje x, representado en grados con valores que van desde -180 a 180.  Esto representa un movimiento de frente hacia atrás del dispositivo.
  • -
  • {{ domxref("DeviceOrientationEvent.gamma") }} representa el movimiento del dispositivo alrededor del eje y, representado en grados con valores que van de -90 a 90. Esto representa un movimiento de izquierda a derecha del dispositivo.
  • -
- -

Ejemplo de orientación

- -

Este ejemplo va a funcionar en cualquier nevegador que soporte el evento {{event("deviceorientation")}} y funcione en un dispositivo con capacidades de detectar la orientación.

- -

Imaginemos una pelota en un jardin:

- -
<div class="garden">
-  <div class="ball"></div>
-</div>
-
-<pre class="output"></pre>
-
- -

Este jardin tiene 200 pixeles de ancho (Si, es uno pequeño), y la pelota esta en el centro:

- -
.garden {
-  position: relative;
-  width : 200px;
-  height: 200px;
-  border: 5px solid #CCC;
-  border-radius: 10px;
-}
-
-.ball {
-  position: absolute;
-  top   : 90px;
-  left  : 90px;
-  width : 20px;
-  height: 20px;
-  background: green;
-  border-radius: 100%;
-}
-
- -

Ahora, si nosotros movemos nuestro dispositivo, la pelota va a moverse acorde a este:

- -
var ball   = document.querySelector('.ball');
-var garden = document.querySelector('.garden');
-var output = document.querySelector('.output');
-
-var maxX = garden.clientWidth  - ball.clientWidth;
-var maxY = garden.clientHeight - ball.clientHeight;
-
-function handleOrientation(event) {
-  var x = event.beta;  // In degree in the range [-180,180]
-  var y = event.gamma; // In degree in the range [-90,90]
-
-  output.innerHTML  = "beta : " + x + "\n";
-  output.innerHTML += "gamma: " + y + "\n";
-
-  // Because we don't want to have the device upside down
-  // We constrain the x value to the range [-90,90]
-  if (x >  90) { x =  90};
-  if (x < -90) { x = -90};
-
-  // To make computation easier we shift the range of
-  // x and y to [0,180]
-  x += 90;
-  y += 90;
-
-  // 10 is half the size of the ball
-  // It center the positioning point to the center of the ball
-  ball.style.top  = (maxX*x/180 - 10) + "px";
-  ball.style.left = (maxY*y/180 - 10) + "px";
-}
-
-window.addEventListener('deviceorientation', handleOrientation);
-
- -

Aqui el resultado en vivo:

- -
{{ EmbedLiveSample('Orientation_example', '230', '260') }}
- -
-

Tener en cuenta: Chrome y Firefox no manejan los angulos de la misma forma, asi que en algunos ejes la dirección se invierte.

-
- -

Procesando eventos de movimiento

- -

Eventos de movimiento son manejados de la misma manera que la orientación, con la excepción de que estos tienen sus propios nombres de evento: {{ event("devicemotion") }}

- -
window.addEventListener("devicemotion", handleMotion, true);
- -

Lo que realmente ha cambiado es la información proporcionada en {{ domxref("DeviceMotionEvent") }} objeto pasado como parametro de la función HandleMotion.

- -

El evento de movimiento tiene cuatro propiedades:

- -
    -
  • {{ domxref("DeviceMotionEvent.acceleration") }}
  • -
  • {{ domxref("DeviceMotionEvent.accelerationIncludingGravity") }}
  • -
  • {{ domxref("DeviceMotionEvent.rotationRate") }}
  • -
  • {{ domxref("DeviceMotionEvent.interval") }}
  • -
- -

Valores de movimiento explicados

- -

{{ domxref("DeviceMotionEvent") }} proporciona a los desarrolladores web información sobre la velocidad de los cambios de la posición y orientación del dispositivo. Los cambios son proporcionados por sus tres ejes (ver Datos de orientación y movimiento explicados por más detalles).

- -

Para {{domxref("DeviceMotionEvent.acceleration","acceleration")}} y {{domxref("DeviceMotionEvent.accelerationIncludingGravity","accelerationIncludingGravity")}}, los ejes corresponden a lo siguiente:

- -
    -
  • x: Representa el eje de oeste a este.
  • -
  • y: Representa el eje de sur a norte.
  • -
  • z: Representa el eje perpendicular al suelo.
  • -
- -

Para {{domxref("DeviceMotionEvent.rotationRate","rotationRate")}}, la situación es un poco diferente; la información corresponde a lo siguiente en cada caso:

- -
    -
  • alpha: Representa la velocidad de rotación a lo largo del eje perpendicular a la pantalla ( teclado para desktop).
  • -
  • beta: Representa la velocidad de rotación  a lo largo del eje que va de la izquierda a la derecha del plano de la pantalla (o teclado para desktop).
  • -
  • gamma: Representa la velocidad de rotación  a lo largo del eje que va desde la parte inferior a la parte superrior del plano de la pantalla (o teclado para desktop).
  • -
- -

Finalmente, {{domxref("DeviceMotionEvent.interval","interval")}} representa el intervalo de tiempo, en milisegundos, en el que los datos han sido obtenidos del dispositivo.

- -

Especificaciones

- - - - - - - - - - - - - - - - -
EspecificaciónEstadoComentario
{{SpecName('Device Orientation')}}{{Spec2('Device Orientation')}}Especificación inicial.
- -

Compatibilidad con navegadores

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
{{domxref("DeviceOrientationEvent")}}7.03.6[1]
- 6
{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
{{domxref("DeviceMotionEvent")}}{{ CompatVersionUnknown() }}6{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
{{domxref("DeviceOrientationEvent")}}3.03.6[1]
- 6
{{ CompatNo() }}{{ CompatNo() }}4.2
{{domxref("DeviceMotionEvent")}}{{ CompatVersionUnknown() }}6{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
-
- -
-

Note: gyronorm.js es un polyfill para normalizar los datos del acelerómetro y giroscopio en dispositivos móviles. Esto es útil para superar algunas de las diferencias en la compatibilidad del dispositivo con la orientación del dispositivo..

-
- -

Gecko implementation notes

- -
    -
  1. Firefox 3.6, 4, and 5 supported mozOrientation versus the standard {{domxref("DeviceOrientationEvent")}} event
  2. -
- -

Vea también

- - diff --git a/files/es/web/api/document_object_model/events/index.html b/files/es/web/api/document_object_model/events/index.html deleted file mode 100644 index 5f2c1b47cf..0000000000 --- a/files/es/web/api/document_object_model/events/index.html +++ /dev/null @@ -1,73 +0,0 @@ ---- -title: Eventos y el DOM -slug: Web/API/Document_Object_Model/Events -tags: - - DOM - - Guía -translation_of: Web/API/Document_Object_Model/Events -original_slug: Referencia_DOM_de_Gecko/Eventos ---- -

Introducción

- -

Este capítulo describe el Modelo de Eventos del DOM. Se describe la interfaz Event, así como las interfaces para el registro de eventos en los nodos del DOM, y los oyentes de eventos, y varios ejemplos más largos muestran cómo se relacionan entre sí las diversas interfaces de eventos.

- -

Hay un diagrama excelente que explica claramente las tres fases del flujo de eventos a través del DOM en el borrador DOM Level 3 Events.

- -

Vea también el Ejemplo 5: Propagación de eventos en el capítulo de Ejemplos para un ejemplo más detallado de cómo los eventos se mueven a través del DOM.

- -

Registrando oyentes de eventos

- -

Hay 3 formas de registrar gestores de eventos para un elemento DOM.

- -

EventTarget.addEventListener

- -
// Se supone que myButton es un elemento de botón
-myButton.addEventListener('click', function(){alert('Hello world');}, false);
-
- -

Este es el método que debe usar en las páginas web modernas. 

- -

Nota: Internet Explorer 6-8 no admite este método, ofreciendo una API similar {{domxref("EventTarget.attachEvent")}} en su lugar. Para la compatibilidad entre navegadores utilice una de las muchas bibliotecas de JavaScript disponibles.

- -

Se pueden encontrar más detalles en la página de referencia {{domxref("EventTarget.addEventListener")}}.

- -

Atributo HTML

- -
<button onclick="alert('Hello world!')">
-
- -

El código de JavaScript en el atributo pasa el objeto Event por medio del parámetro event. El valor de retorno se trata de una manera especial, descrita en la especificación HTML.

- -

Debe evitarse esta forma. Hace que el marcado sea más grande y menos legible. El comitido del contenido/estructura y del comportamiento no están bien separadas, por lo que es más difícil encontrar un error.

- -

Propiedades del elemento DOM

- -
// Se supone que myButton es un elemento de botón
-myButton.onclick = function(event){alert('Hello world');};
-
- -

La función se puede defirnir para que tome un parámetro event. El valor de retorno se trata de una manera especial, descrita en la especificación HTML.

- -

El problema con este método es que solo se puede establecer un gestor por elemento y por evento.

- -

Accediendo a las Interfaces de eventos

- -

Los controladores de eventos se pueden adjuntar a varios objetos, incluidos los elementos DOM, documentos, al objeto window, etc. Cuando se produce un evento, se crea un objeto de evento y se pasa secuencialmente a los oyentes del evento.

- -

Se puede acceder a la interfaz {{domxref ("Evento")}} desde la función del gestor, a través del objeto de evento pasado como primer argumento. El siguiente ejemplo simple muestra cómo se pasa un objeto de evento a la función del controlador de eventos, y se puede usar desde dentro de una de esas funciones.

- -
function foo(evt) {
-  // al parámetro evt se le asigna automáticamente el objeto event
-  alert(evt);
-}
-table_el.onclick = foo;
-
- - - - diff --git a/files/es/web/guide/events/event_handlers/index.html b/files/es/web/guide/events/event_handlers/index.html deleted file mode 100644 index f7bd9ac9e1..0000000000 --- a/files/es/web/guide/events/event_handlers/index.html +++ /dev/null @@ -1,133 +0,0 @@ ---- -title: Manejadores de eventos en el DOM -slug: Web/Guide/Events/Event_handlers -translation_of: Web/Guide/Events/Event_handlers -original_slug: Web/Guide/DOM/Events/eventos_controlador ---- -

La plataforma Web provee varias formas de recibir notificaciones de los eventos del DOM.  Dos de las formas más comunes son: la general {{domxref("EventTarget.addEventListener", "addEventListener()")}} y un conjunto específico de controladores de eventos específicos. Esta página se enfoca en los detalles de cómo funcionan estos.

- -

Registering on-event handlers

- -

Los controladores on-event son un grupo de propiedades ofrecidas por los elementos del DOM para ayudar a manejar cómo los elementos reaccionan a los eventos. Los elementos pueden ser interactivos (por ejemplo: enlaces, botones, imagenes, formularios) or non-interactive (e.g. the base document). Los eventos pueden ser cuando se haga un click, detectar cuando se presione una tecla,  enfocarse, entre otros. Los handlers on-event son comunmente denominados como el evento al cual deben reaccionar, como ser onclick, onkeypress, onfocus, etc.

- -

Pueden especificar un controlador de evento on<...> para un evento en particular (como {{event("click")}}) como un opbjeto determinado de diferentes formas:

- -
    -
  • Usando el HTML {{Glossary("atributo")}} llamados on{eventtype} en un elemento, por ejemplo:
    - <button onclick="return handleClick(event);">,
  • -
  • O seteandolo {{Glossary("property/JavaScript", "property")}} desde JavaScript, por ejemplo:
    - document.getElementById("mybutton").onclick = function(event) { ... }.
  • -
- -

Un controlador onevent

- -

Notese que cada objeto puede tener sólo un controlador on-event para un evento dado (though that handler could call multiple sub-handlers). This is why {{domxref("EventTarget.addEventListener", "addEventListener()")}} is often the better way to get notified of events, especially when wishing to apply various event handlers independently from each other, even for the same event and/or to the same element.

- -

Also note that on-event handlers are called automatically, not at the programmer's will (although you can, like  mybutton.onclick(myevent); ) since they serve more as placeholders to which a real handler function can be assigned.

- -

Non-element objects

- -

Event handlers can also be set using properties on many non-element objects that generate events, including {{ domxref("window") }}, {{ domxref("document") }}, {{ domxref("XMLHttpRequest") }}, and others, for example:

- -
xhr.onprogress = function() { ... }
- -

Details

- -

The value of HTML on<...> attributes and corresponding  JavaScript properties

- -

A handler registered via an on<...> attribute will be available via the corresponding on<...> property, but not the other way around:

- -
<div id="a" onclick="alert('old')">Open the Developer Tools Console to see the output.</div>
-
-<script>
-window.onload = function () {
-  var div = document.getElementById("a");
-  console.log("Attribute reflected as a property: ", div.onclick.toString());
-  // Prints: function onclick(event) { alert('old') }
-  div.onclick = function() { alert('new') };
-  console.log("Changed property to: ", div.onclick.toString());
-  // Prints: function () { alert('new') }
-  console.log("Attribute value is unchanged: ", div.getAttribute("onclick"));
-  // Prints: alert('old')
-}
-</script>
- -

For historical reasons, some attributes/properties on the {{HTMLElement("body")}} and {{HTMLElement("frameset")}} elements actually set event handlers on their parent {{domxref("Window")}} object. (The HTML specification names these: onblur, onerror, onfocus, onload, onscroll.)

- -

Event handler's parameters, this binding, and the return value

- -

When the event handler is specified as an HTML attribute, the specified code is wrapped into a function with the following parameters:

- -
    -
  • event - for all event handlers, except {{domxref("GlobalEventHandlers.onerror", "onerror")}}.
  • -
  • event, source, lineno, colno, and error for the {{domxref("GlobalEventHandlers.onerror", "onerror")}} event handler. Note that the event parameter actually contains the error message as string.
  • -
- -

When the event handler is invoked, the this keyword inside the handler is set to the DOM element on which the handler is registered. For more details see the this keyword documentation.

- -

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 "The event handler processing algorithm" in the HTML specification.

- -

When the event handler is invoked

- -

TBD (non-capturing listener)

- -

Terminology

- -

The term event handler may be used to refer to:

- -
    -
  • any function or object registered to be notified of events,
  • -
  • or, more specifically, to the mechanism of registering event listeners via on... attributes in HTML or properties in web APIs, such as <button onclick="alert(this)"> or window.onload = function() { /* ... */ }.
  • -
- -

When discussing the various methods of listening to events,

- -
    -
  • event listener refers to a function or object registered via {{domxref("EventTarget.addEventListener()")}},
  • -
  • whereas event handler refers to a function registered via on... attributes or properties.
  • -
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML5 W3C')}}
- -

Browser compatibility

- -

Event handler changes in Firefox 9

- -

In order to better match the specifications, and improve cross-browser compatibility, the way event handlers were implemented at a fundamental level changed in Gecko 9.0 {{ geckoRelease("9.0") }}.

- -

Specifically, in the past, event handlers were not correctly implemented as standard IDL attributes. In Gecko 9.0, this was changed. Because of this, certain behaviors of event handlers in Gecko have changed. In particular, they now behave in all the ways standard IDL attributes behave. In most cases, this shouldn't affect web or add-on content at all; however, there are a few specific things to watch out for.

- -

Detecting the presence of event handler properties

- -

You can now detect the presence of an event handler property (that is, for example, onload), using the JavaScript in operator. For example:

- -
if ("onsomenewfeature" in window) {
-  /* do something amazing */
-}
-
- -

Event handlers and prototypes

- -

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 Window.prototype.onload anymore. In the past, event handlers (onload, 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.

diff --git a/files/es/web/guide/events/index.html b/files/es/web/guide/events/index.html deleted file mode 100644 index a9e55742fa..0000000000 --- a/files/es/web/guide/events/index.html +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: Event developer guide -slug: Web/Guide/Events -tags: - - DOM - - Event - - Guide - - NeedsTranslation - - TopicStub - - events -translation_of: Web/Guide/Events -original_slug: Web/Guide/DOM/Events ---- -

{{draft()}}

-

Everything you need to know about events will go under here. We're working on cleanup here now.

-

Docs

-

{{LandingPageListSubpages}}

diff --git a/files/es/web/guide/events/orientation_and_motion_data_explained/index.html b/files/es/web/guide/events/orientation_and_motion_data_explained/index.html deleted file mode 100644 index 8c700f6a71..0000000000 --- a/files/es/web/guide/events/orientation_and_motion_data_explained/index.html +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: Explicación de los datos de orientación y movimiento -slug: Web/Guide/Events/Orientation_and_motion_data_explained -translation_of: Web/Guide/Events/Orientation_and_motion_data_explained -original_slug: >- - Web/Guide/API/DOM/Events/Orientation_and_motion_data_explained/Orientation_and_motion_data_explained ---- -

{{ Draft() }}

-

Sumario

-

Cuando se utiliza la orientación y los eventos de movimiento, es importante entender cuáles son los significados de los valores en el navegador. En este artículo se proporciona información acerca de los sistemas de coordenadas en el juego y la forma de usarlos.

-
-

Atención: Actualmente, Firefox y Chrome no soporta la orientación de la misma forma. Ten cuidado con esto cuando sea imprementado en un navegador u otro.

-
-

Acerca de los marcos de coordenadas

-

Un marco de coordenadas en un sistema en el que la orientacion de los tres ejers (X, Y y Z) se definen en referencia a un objeto. Hay dos marcos de coordenadas a considerar cuando se utiliza eventos de orientación y el movimiento:

-

Marco de coordenadas terrestres

-

El marco de coordenadas de terrestres es el sistema de coordenadas fijado en el centro de la Tierra, es decir, los ejes están alineados sobre la base de la fuerza de la gravedad y la orientación norte magnético estándar. Utilizamos las letras mayúsculas ("X", "Y" y "Z") para describir los ejes del sistema de coordenadas terrestre.

-
    -
  • El eje X sigue a lo largo (profuncidad) del plano de tierra, perpendicular al eje Y y positiva hacia el este (y por lo tanto negativa hacia el oeste).
  • -
  • El eje Y sigue a lo largo(ancho) del plano de tierra, y es positivo hacia el norte verdadero (es decir, el Polo Norte, el norte no es magnético) y negativo hacia la verdadera sur.
  • -
  • El eje Z es perpendicular al plano de tierra, piensa en él como una línea trazada entre el dispositivo y el centro de la Tierra. El valor de la coordenada Z es positivo hacia arriba (distancia desde el centro de la Tierra) y negativo hacia abajo (hacia el centro de la Tierra).
  • -
-

 

-

-

 

-

Marco de coordenadas del dispositivo

-

El marco de coordenadas del dispositivo es el marco de la coordinación fijada en el centro del dispositivo. Utilizamos letras minúsculas ("x", "y" y "z") para describir los ejes de las coordenadas del del dispositivo

-

axes.png

-
    -
  • El eje x está en el plano de la pantalla y es positiva hacia la derecha y negativa hacia la izquierda.
  • -
  • El eje y está en el plano de la pantalla y es positiva hacia la parte superior y negativa hacia la parte inferior.
  • -
  • El eje z es perpendicular a la pantalla o teclado, y es positivo que se extiende hacia fuera de la pantalla.
  • -
-
- Nota: En un teléfono o tableta, la orientación del dispositivo siempre se considera en relación con la orientación estándar de la pantalla, lo que es la orientación "retrato" en la mayoría de los dispositivos. En una computadora portátil, la orientación se considera en relación con el teclado. Si desea detectar cambios en la orientación del dispositivo con el fin de compensar, se puede utilizar el evento orientationChange.
-

Sobre la rotación

-

La rotación se describe alrededor de cualquier eje dado en términos del número de grados de diferencia entre el marco de coordenadas del dispositivo y el marco de coordenadas de la Tierra, y se mide en grados.

-

Alpha

-

Rotación alrededor del eje z - es decir, girando el dispositivo - hace que el ángulo de rotación alfa cambie:

-

alpha.png

-

El ángulo alfa es de 0 °, cuando la parte superior del dispositivo se apunta directamente hacia el polo norte de la Tierra, y aumenta a medida que el dispositivo se gira hacia la izquierda.

-

Beta

-

Rotación alrededor del eje X - es decir, inclinando el dispositivo desde o hacia el usuario - hace que el ángulo de giro beta cambie:

-

beta.png

-

El ángulo beta es de 0 ° en la parte superior e inferior del dispositivo son la misma distancia de la superficie de la Tierra, y aumenta hacia 180 ° como el dispositivo se inclina hacia adelante y disminuye hacia -180 ° como el dispositivo se inclina hacia atrás.

-

Gamma

-

Rotación alrededor del eje Y - es decir, la inclinación del dispositivo hacia la izquierda o hacia la derecha - hace que el ángulo de giro gamma cambie:

-

gamma.png

-

El ángulo gamma es 0 °, cuando los lados izquierdo y derecho del dispositivo son la misma distancia de la superficie de la Tierra, y aumenta hacia 90 ° como el dispositivo se inclina hacia la derecha, y hacia -90 ° como el dispositivo se inclina hacia el izquierda.

diff --git a/files/fi/_redirects.txt b/files/fi/_redirects.txt index c2937a661e..f2e8d44654 100644 --- a/files/fi/_redirects.txt +++ b/files/fi/_redirects.txt @@ -1,3 +1,8 @@ +# DO NOT EDIT THIS FILE MANUALLY. +# Use the CLI instead: +# +# yarn content add-redirect +# # FROM-URL TO-URL /fi/docs/DOM /fi/docs/Web/API/Document_Object_Model /fi/docs/DOM/navigator.doNotTrack /fi/docs/Web/API/Navigator/doNotTrack @@ -28,6 +33,7 @@ /fi/docs/Skinin_luominen_Firefoxiin/Aloittaminen /fi/docs/orphaned/Skinin_luominen_Firefoxiin/Aloittaminen /fi/docs/Skinin_luominen_Firefoxiin:Aloittaminen /fi/docs/orphaned/Skinin_luominen_Firefoxiin/Aloittaminen /fi/docs/Teemat /fi/docs/orphaned/Teemat +/fi/docs/Web/Guide/Events /fi/docs/orphaned/Web/Guide/Events /fi/docs/WebGL /fi/docs/Web/API/WebGL_API /fi/docs/demos /fi/docs/orphaned/demos /fi/docs/demos/detail /fi/docs/orphaned/demos/detail diff --git a/files/fi/_wikihistory.json b/files/fi/_wikihistory.json index e27e7c560b..46b1d2e151 100644 --- a/files/fi/_wikihistory.json +++ b/files/fi/_wikihistory.json @@ -95,12 +95,6 @@ "chrisdavidmills" ] }, - "Web/Guide/Events": { - "modified": "2019-03-18T21:37:53.387Z", - "contributors": [ - "gportioli" - ] - }, "Web/HTML": { "modified": "2019-09-10T15:19:38.441Z", "contributors": [ @@ -356,5 +350,11 @@ "contributors": [ "Prasanth" ] + }, + "orphaned/Web/Guide/Events": { + "modified": "2019-03-18T21:37:53.387Z", + "contributors": [ + "gportioli" + ] } } \ No newline at end of file diff --git a/files/fi/orphaned/web/guide/events/index.html b/files/fi/orphaned/web/guide/events/index.html new file mode 100644 index 0000000000..43aec7dec1 --- /dev/null +++ b/files/fi/orphaned/web/guide/events/index.html @@ -0,0 +1,54 @@ +--- +title: Event developer guide +slug: orphaned/Web/Guide/Events +tags: + - DOM + - Event + - Guide + - NeedsTranslation + - NeedsUpdate + - TopicStub + - events +translation_of: Web/Guide/Events +original_slug: Web/Guide/Events +--- +

{{draft()}}

+ +

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.

+ +

The overview page 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.

+ +

The custom events page 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.

+ +

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.

+ +

The device 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 page on orientation coordinate systems and the page on the use of 3D transforms. That is different, but similar, to the change in device vertical orientation. 

+ +

The window in which the browser is displayed can trigger events; for example, change size if the user maximizes the window or otherwise changes it.

+ +

The process loading of a web page can 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.

+ +

The user interaction with the web page contents can 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:

+ + + +

The modification of the web page in structure or content might trigger some events, as explained in the mutation events page, but the use of these events has been deprecated in favour of the lighter Mutation Observer approach.

+ +

The media streams embedded in the HTML documents might trigger some events, as explained in the media events page.

+ +

The network requests made by a web page might trigger some events.

+ +

There are many other sources of events defined by web browsers for which pages are not yet available in this guide.

+ +
+

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.

+
+ +

Docs

+ +

{{LandingPageListSubpages}}

diff --git a/files/fi/web/guide/events/index.html b/files/fi/web/guide/events/index.html deleted file mode 100644 index 0196a78f5a..0000000000 --- a/files/fi/web/guide/events/index.html +++ /dev/null @@ -1,53 +0,0 @@ ---- -title: Event developer guide -slug: Web/Guide/Events -tags: - - DOM - - Event - - Guide - - NeedsTranslation - - NeedsUpdate - - TopicStub - - events -translation_of: Web/Guide/Events ---- -

{{draft()}}

- -

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.

- -

The overview page 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.

- -

The custom events page 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.

- -

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.

- -

The device 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 page on orientation coordinate systems and the page on the use of 3D transforms. That is different, but similar, to the change in device vertical orientation. 

- -

The window in which the browser is displayed can trigger events; for example, change size if the user maximizes the window or otherwise changes it.

- -

The process loading of a web page can 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.

- -

The user interaction with the web page contents can 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:

- - - -

The modification of the web page in structure or content might trigger some events, as explained in the mutation events page, but the use of these events has been deprecated in favour of the lighter Mutation Observer approach.

- -

The media streams embedded in the HTML documents might trigger some events, as explained in the media events page.

- -

The network requests made by a web page might trigger some events.

- -

There are many other sources of events defined by web browsers for which pages are not yet available in this guide.

- -
-

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.

-
- -

Docs

- -

{{LandingPageListSubpages}}

diff --git a/files/fr/_redirects.txt b/files/fr/_redirects.txt index b6cf255d2a..430ba7ed9e 100644 --- a/files/fr/_redirects.txt +++ b/files/fr/_redirects.txt @@ -3625,6 +3625,7 @@ /fr/docs/Web/API/Console/erreur /fr/docs/Web/API/Console/error /fr/docs/Web/API/Coordinates /fr/docs/Web/API/GeolocationCoordinates /fr/docs/Web/API/DOMTokenList/DOMTokenList.add() /fr/docs/Web/API/DOMTokenList/add +/fr/docs/Web/API/Detecting_device_orientation /fr/docs/orphaned/Web/API/Detecting_device_orientation /fr/docs/Web/API/DeviceOrientationEvent.absolute /fr/docs/Web/API/DeviceOrientationEvent/absolute /fr/docs/Web/API/DeviceRotationRate /fr/docs/Web/API/DeviceMotionEventRotationRate /fr/docs/Web/API/DeviceRotationRate/alpha /fr/docs/Web/API/DeviceMotionEventRotationRate/alpha @@ -3661,9 +3662,10 @@ /fr/docs/Web/API/DocumentOrShadowRoot/elementsFromPoint /fr/docs/Web/API/Document/elementsFromPoint /fr/docs/Web/API/DocumentOrShadowRoot/getSelection /fr/docs/Web/API/Document/getSelection /fr/docs/Web/API/DocumentOrShadowRoot/styleSheets /fr/docs/Web/API/Document/styleSheets +/fr/docs/Web/API/Document_Object_Model/Events /fr/docs/orphaned/Web/API/Document_Object_Model/Events /fr/docs/Web/API/Document_Object_Model/Exemples /fr/docs/Web/API/Document_Object_Model/Examples /fr/docs/Web/API/Document_Object_Model/Introduction_au_DOM /fr/docs/Web/API/Document_Object_Model/Introduction -/fr/docs/Web/API/Document_Object_Model/Les_évènements_et_le_DOM /fr/docs/Web/API/Document_Object_Model/Events +/fr/docs/Web/API/Document_Object_Model/Les_évènements_et_le_DOM /fr/docs/orphaned/Web/API/Document_Object_Model/Events /fr/docs/Web/API/Document_Object_Model/Localisation_des_éléments_DOM_avec_les_sélecteurs /fr/docs/Web/API/Document_object_model/Locating_DOM_elements_using_selectors /fr/docs/Web/API/Document_Object_Model/Préface /fr/docs/conflicting/Web/API/Document_Object_Model_03f6e13c52ad7c539d9b4c33c51ac4a3 /fr/docs/Web/API/Document_Object_Model/document /fr/docs/Web/API/Document @@ -4417,9 +4419,9 @@ /fr/docs/Web/Guide/CSS /fr/docs/Learn/CSS /fr/docs/Web/Guide/CSS/Flexible_boxes /fr/docs/Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox /fr/docs/Web/Guide/DOM /fr/docs/conflicting/Web/API/Document_Object_Model_656f0e51418b39c498011268be9b3a10 -/fr/docs/Web/Guide/DOM/Events /fr/docs/Web/Guide/Events +/fr/docs/Web/Guide/DOM/Events /fr/docs/orphaned/Web/Guide/Events /fr/docs/Web/Guide/DOM/Events/Creating_and_triggering_events /fr/docs/orphaned/Web/Guide/Events/Creating_and_triggering_events -/fr/docs/Web/Guide/DOM/Events/Les_données_d_orientation_et_de_mouvement_expliquées /fr/docs/Web/Guide/Events/Orientation_and_motion_data_explained +/fr/docs/Web/Guide/DOM/Events/Les_données_d_orientation_et_de_mouvement_expliquées /fr/docs/orphaned/Web/Guide/Events/Orientation_and_motion_data_explained /fr/docs/Web/Guide/DOM/Events/Touch_events /fr/docs/Web/API/Touch_events /fr/docs/Web/Guide/DOM/Events/Touch_events/Gérer_à_la_fois_événement_tactile_et_événement_de_la_souris /fr/docs/Web/API/Touch_events/Supporting_both_TouchEvent_and_MouseEvent /fr/docs/Web/Guide/DOM/Manipuler l'historique du navigateur /fr/docs/Web/API/History_API @@ -4427,7 +4429,9 @@ /fr/docs/Web/Guide/DOM/Manipuler_historique_du_navigateur /fr/docs/Web/API/History_API /fr/docs/Web/Guide/DOM/Manipuler_historique_du_navigateur/Example /fr/docs/Web/API/History_API/Example /fr/docs/Web/Guide/DOM/Using_full_screen_mode /fr/docs/Web/API/Fullscreen_API +/fr/docs/Web/Guide/Events /fr/docs/orphaned/Web/Guide/Events /fr/docs/Web/Guide/Events/Creating_and_triggering_events /fr/docs/orphaned/Web/Guide/Events/Creating_and_triggering_events +/fr/docs/Web/Guide/Events/Orientation_and_motion_data_explained /fr/docs/orphaned/Web/Guide/Events/Orientation_and_motion_data_explained /fr/docs/Web/Guide/Graphics/Dessiner_avec_canvas /fr/docs/conflicting/Web/API/Canvas_API/Tutorial /fr/docs/Web/Guide/HTML /fr/docs/Learn/HTML /fr/docs/Web/Guide/HTML/Astuces_de_création_de_pages_HTML_à_affichage_rapide /fr/docs/Learn/HTML/Howto/Author_fast-loading_HTML_pages @@ -5704,7 +5708,7 @@ /fr/docs/Web/XSLT/Éléments/element /fr/docs/Web/XSLT/Element/element /fr/docs/WebAPI /fr/docs/conflicting/Web/API_dd04ca1265cb79b990b8120e5f5070d3 /fr/docs/WebAPI/Battery_Status /fr/docs/Web/API/Battery_status_API -/fr/docs/WebAPI/Detecting_device_orientation /fr/docs/Web/API/Detecting_device_orientation +/fr/docs/WebAPI/Detecting_device_orientation /fr/docs/orphaned/Web/API/Detecting_device_orientation /fr/docs/WebAPI/Network_Information /fr/docs/Web/API/Network_Information_API /fr/docs/WebAPI/Pointer_Lock /fr/docs/Web/API/Pointer_Lock_API /fr/docs/WebAPI/Proximity /fr/docs/Web/API/Proximity_Events diff --git a/files/fr/_wikihistory.json b/files/fr/_wikihistory.json index 271068eb88..59a24a90c4 100644 --- a/files/fr/_wikihistory.json +++ b/files/fr/_wikihistory.json @@ -33255,12 +33255,6 @@ "Fredchat" ] }, - "Web/API/Document_Object_Model/Events": { - "modified": "2019-03-18T21:39:20.100Z", - "contributors": [ - "loella16" - ] - }, "Web/API/Document_object_model/Locating_DOM_elements_using_selectors": { "modified": "2019-03-18T21:39:30.176Z", "contributors": [ @@ -35215,19 +35209,6 @@ "wordsbybird" ] }, - "Web/Guide/Events": { - "modified": "2020-08-30T07:20:46.985Z", - "contributors": [ - "Voulto", - "Sheppy" - ] - }, - "Web/Guide/Events/Orientation_and_motion_data_explained": { - "modified": "2019-03-18T21:41:00.371Z", - "contributors": [ - "loella16" - ] - }, "Web/API/Touch_events/Supporting_both_TouchEvent_and_MouseEvent": { "modified": "2019-03-18T21:33:21.001Z", "contributors": [ @@ -43462,18 +43443,6 @@ "Fredchat" ] }, - "Web/API/Detecting_device_orientation": { - "modified": "2019-03-23T23:28:22.437Z", - "contributors": [ - "mgagnon555", - "a-mt", - "tregagnon", - "Fredchat", - "FredB", - "achraf", - "darnuria" - ] - }, "Web/API/Network_Information_API": { "modified": "2020-10-15T21:24:14.258Z", "contributors": [ @@ -45335,5 +45304,36 @@ "yasakura_", "jmh" ] + }, + "orphaned/Web/API/Detecting_device_orientation": { + "modified": "2019-03-23T23:28:22.437Z", + "contributors": [ + "mgagnon555", + "a-mt", + "tregagnon", + "Fredchat", + "FredB", + "achraf", + "darnuria" + ] + }, + "orphaned/Web/API/Document_Object_Model/Events": { + "modified": "2019-03-18T21:39:20.100Z", + "contributors": [ + "loella16" + ] + }, + "orphaned/Web/Guide/Events": { + "modified": "2020-08-30T07:20:46.985Z", + "contributors": [ + "Voulto", + "Sheppy" + ] + }, + "orphaned/Web/Guide/Events/Orientation_and_motion_data_explained": { + "modified": "2019-03-18T21:41:00.371Z", + "contributors": [ + "loella16" + ] } } \ No newline at end of file diff --git a/files/fr/orphaned/web/api/detecting_device_orientation/index.html b/files/fr/orphaned/web/api/detecting_device_orientation/index.html new file mode 100644 index 0000000000..42b8cec296 --- /dev/null +++ b/files/fr/orphaned/web/api/detecting_device_orientation/index.html @@ -0,0 +1,220 @@ +--- +title: Détecter l'orientation de l'appareil +slug: orphaned/Web/API/Detecting_device_orientation +tags: + - Device Orientation + - Firefox OS + - Mobile + - Motion + - Orientation +translation_of: Web/API/Detecting_device_orientation +original_slug: Web/API/Detecting_device_orientation +--- +

{{SeeCompatTable}}

+ +

Résumé

+ +

De plus en plus d'appareils connectés à Internet sont capable de déterminer leur orientation. C'est-à-dire qu'ils peuvent fournir des données indiquant des changements dans leur orientation par rapport à la gravité. En particulier les appareils portables, comme les téléphones mobiles, peuvent utiliser cette information pour effectuer automatiquement une rotation de l'écran, afin de toujours proposer la meilleure disposition possible pour le contenu à afficher.

+ +

Il existe deux événements JavaScript pour gérer l'orientation. Le premier est {{domxref("DeviceOrientationEvent")}}, qui est envoyé quand l'accéléromètre détecte un changement d'orientation de l'appareil. En recevant et en analysant les données fournies par ces événements d'orientation, il est possible de répondre de manière interactive aux changements d'orientation et d'élévation causés par les mouvements imprimés à l'appareil par l'utilisateur.

+ +

Le second événement est {{ domxref("DeviceMotionEvent") }}, qui est envoyé quand un changement d’accélération est ajouté. Il est différent de {{domxref("DeviceOrientationEvent")}}, car il écoute les changements d'accélération par opposition à l'orientation. Parmi les capteurs capables de détecter {{ domxref("DeviceMotionEvent") }}, on trouve les capteurs des ordinateurs portables utilisés pour protéger des chutes les périphériques de stockage. Ils sont communément présents dans les appareils mobiles (tablettes, téléphones intelligents).

+ +

Traitement des événements d'orientation

+ +

Tout ce dont vous avez besoin pour commencer à recevoir les changements d'orientation est d’écouter l’événement {{ event("deviceorientation") }} :

+ +
+

Note: gyronorm.js est un polyfill pour normaliser les données de l'accéléromètre et du gyroscope sur les appareils mobiles. C'est utile pour surmonter certaines différences dans la prise en charge des périphériques pour l'orientation du périphérique.

+
+ +
window.addEventListener("deviceorientation", handleOrientation, true);
+
+ +

Après l’enregistrement de votre gestionnaire d'événements (event listener en anglais), dans ce cas, une fonction JS appelée handleOrientation(), votre fonction d'écoute est appelée périodiquement pour récupérer les données de l'orientation mise à jour.

+ +

L'événement d'orientation contient quatre valeurs ::

+ +
    +
  • {{domxref("DeviceOrientationEvent.absolute")}}
  • +
  • {{domxref("DeviceOrientationEvent.alpha")}}
  • +
  • {{domxref("DeviceOrientationEvent.beta")}}
  • +
  • {{domxref("DeviceOrientationEvent.gamma")}}
  • +
+ +

La fonction gérant l’événement pourrait ressembler à ceci :

+ +
function handleOrientation(event) {
+  var absolute = event.absolute;
+  var alpha    = event.alpha;
+  var beta     = event.beta;
+  var gamma    = event.gamma;
+
+  // Faites quelque chose avec les données acquises. ;)
+}
+
+ +

Détail des valeurs d'orientation

+ +

La valeur reportée pour chaque axe indique l'angle de rotation autour d'un axe donné, en référence à un système de coordonnées standard. Ces valeurs sont décrites de façon plus détaillée dans cet article Orientation et déplacement expliquée.

+ +
    +
  • La valeur {{ domxref("DeviceOrientationEvent.alpha") }} représente le mouvement de l'appareil, autour de l'axe « z », en degrés sur une échelle de 0° à 360° ;
  • +
  • La valeur {{ domxref("DeviceOrientationEvent.beta") }} représente le mouvement de l'appareil autour de l'axe « y » en degrés, sur une échelle de -180° à 180°.  Cela représente le mouvement d'avant en arrière de l'appareil ;
  • +
  • La valeur {{ domxref("DeviceOrientationEvent.gamma") }} représente le mouvement de l'appareil autour de l'axe « x », exprimée en degrés sur une échelle de -90° à 90°. Cela représente le mouvement de gauche à droite de l'appareil.
  • +
+ +

Exemple d'orientation

+ +

Cet exemple fonctionne sur tout navigateur supportant l’événement {{event("deviceorientation")}} et sur tout appareil capable de détecter son orientation.

+ +

Imaginons une balle dans un jardin :

+ +
<div class="jardin">
+  <div class="balle"></div>
+</div>
+
+<pre class="resultat"></pre>
+
+ +

Ce jardin fait 200 pixels de long (Oui c'est un « petit » jardin !), et la balle est au centre :

+ +
.jardin {
+  position: relative;
+  width : 200px;
+  height: 200px;
+  border: 5px solid #CCC;
+  border-radius: 10px;
+}
+
+.balle {
+  position: absolute;
+  top   : 90px;
+  left  : 90px;
+  width : 20px;
+  height: 20px;
+  background: green;
+  border-radius: 100%;
+}
+
+ +

Maintenant, on définit le déplacement de la balle en fonction de celui de l'appareil :

+ +
var jardin = document.querySelector('.jardin'),
+    balle = document.querySelector('.balle'),
+    resultat = document.querySelector('.resultat'),
+    maxX = jardin.clientWidth  - balle.clientWidth,
+    maxY = jardin.clientHeight - balle.clientHeight;
+
+function handleOrientation(event) {
+  var x = event.beta,  // En degré sur l'interval [-180,180].
+      y = event.gamma; // En degré sur l'interval [-90,90].
+
+  resultat.innerHTML  = "beta : " + x + "<br />";
+  resultat.innerHTML += "gamma: " + y + "<br />";
+
+  // Parce-que l'on ne veut pas avoir l'appareil à l'envers.
+  // On restreint les valeurs de x à l'intervalle [-90,90].
+  if (x >  90) { x =  90};
+  if (x < -90) { x = -90};
+  // Pour rendre le calcul plus simple.
+  // On délimite l'intervalle de x et y sur [0, 180].
+  x += 90;
+  y += 90;
+
+  // 10 est la moitié de la taille de la balle.
+  // Cela centre le point de positionnement au centre de la balle.
+
+  balle.style.top  = (maxX * x / 180 - 10) + "px";
+  balle.style.left = (maxY * y / 180 - 10) + "px";
+}
+
+window.addEventListener('deviceorientation', handleOrientation);
+
+ +

Et voici le résultat en temps réel :

+ +
{{EmbedLiveSample("Exemple_d'orientation", '230', '260')}}
+ +
 
+ +
{{LiveSampleLink("Exemple_d'orientation", "Cliquez ici")}} pour ouvrir cet exemple dans une nouvelle fenêtre;  l'événement {{event("deviceorientation")}} ne marche pas dans les {{HTMLElement("iframe", "iframes")}} cross-origin dans tous les navigateurs.
+ +
 
+ +
+

Attention : Chrome et Firefox ne gèrent pas les angles de la même façon, certaines directions sur les axes sont inversées.

+
+ +

Traiter les événement de mouvement

+ +

Les événements de mouvement gèrent l'orientation de la même façon à l'exception près qu’ils portent un nom d’événement différent : {{event("devicemotion")}}

+ +
window.addEventListener("devicemotion", handleMotion, true);
+
+ +

Ce qui change réellement est l'information fournie par l'objet {{ domxref("DeviceMotionEvent") }} passée comme paramètre par la fonction HandleMotion.

+ +

Les événements de mouvement contiennent quatre propriétés :

+ +
    +
  • {{domxref("DeviceMotionEvent.acceleration")}}
  • +
  • {{domxref("DeviceMotionEvent.accelerationIncludingGravity")}}
  • +
  • {{domxref("DeviceMotionEvent.rotationRate")}}
  • +
  • {{domxref("DeviceMotionEvent.interval")}}
  • +
+ +

Explication des valeurs de mouvement

+ +

L'objet {{ domxref("DeviceMotionEvent") }} fourni aux développeurs Web des informations sur la vitesse de changement d'orientation et de position de l'appareil. Les changements rapportés sont fournis pour les trois axes (voir Orientation et déplacement expliquées pour les détails).

+ +

Pour {{domxref("DeviceMotionEvent.acceleration","acceleration")}} et {{domxref("DeviceMotionEvent.accelerationIncludingGravity","accelerationIncludingGravity")}}, Les axes correspondent à :

+ +
    +
  • x : représente l'axe d'Ouest en Est ;
  • +
  • y : représente l'axe Sud vers Nord :
  • +
  • z : représente l'axe perpendiculaire au sol.
  • +
+ +

Pour {{domxref("DeviceMotionEvent.rotationRate","rotationRate")}}, c'est un peu différent. L'information correspond à :

+ +
    +
  • alpha : représente le ratio de rotation le long de l'axe perpendiculaire à l'écran (ou du clavier au bureau) ;
  • +
  • bêta : représente le ratio de rotation le long de l'axe allant de la gauche vers la droite de l'écran (ou du clavier au bureau) ;
  • +
  • gamma : représente le ratio de rotation le long de l'axe allant du bas vers le haut de l'écran (ou clavier vers le bureau).
  • +
+ +

Au final, {{domxref("DeviceMotionEvent.interval","interval")}} représente l'intervalle de temps, en millisecondes, pour les données générées par l'appareil.

+ +

Spécifications

+ + + + + + + + + + + + + + + + +
SpécificationStatutCommentaires
{{SpecName('Device Orientation')}}{{Spec2('Device Orientation')}}Spécification initiale.
+ +

Compatibilité des navigateurs

+ +

{{Compat("api.DeviceOrientationEvent")}}

+ +

Voir aussi

+ + diff --git a/files/fr/orphaned/web/api/document_object_model/events/index.html b/files/fr/orphaned/web/api/document_object_model/events/index.html new file mode 100644 index 0000000000..7e3d544c5a --- /dev/null +++ b/files/fr/orphaned/web/api/document_object_model/events/index.html @@ -0,0 +1,75 @@ +--- +title: Les évènements et le DOM +slug: orphaned/Web/API/Document_Object_Model/Events +tags: + - API + - DOM + - Guide + - évènements +translation_of: Web/API/Document_Object_Model/Events +original_slug: Web/API/Document_Object_Model/Events +--- +

Introduction

+ +

Ce chapitre décrit le modèle d'événement DOM. L'interface Event elle-même est décrite, ainsi que les interfaces pour l'enregistrement des évènements sur les noeuds dans le DOM, les écouteurs d'évènements et d'autres exemples montrant les relations des différentes interfaces d'évènements entre elles.

+ +

Il existe un excellent diagramme qui explique clairement les trois phases du flux d'évènements à travers le DOM dans le document sur les évènements DOM Niveau 3.

+ +

Voir aussi l'exemple 5 : Propagation des évènements dans le chapitre "Exemples" pour des exemples détaillés sur le déplacement des évènements à travers le DOM.

+ +

Enregistrement des écouteurs d'évènements

+ +

Il y a 3 moyens d'enregistrer les gestionnaires d'évènements pour un élément DOM.

+ +

EventTarget.addEventListener

+ +
// Supposons que myButton est un élément de bouton
+myButton.addEventListener('click', function(){alert('Hello world');}, false);
+
+ +

C'est la méthode à utiliser dans les pages web modernes.

+ +

Note : Internet Explorer 6-8 ne prend pas en charge cette méthode, il offre une API similaire {{domxref("EventTarget.attachEvent")}} à la place. Pour la compatibilité entre navigateurs, utilisez l'une des nombreuses bibliothèques JavaScript disponibles.

+ +

Plus de détails peuvent être trouvés sur la page de référence {{domxref("EventTarget.addEventListener")}}.

+ +

attribut HTML

+ +
<button onclick="alert('Hello world!')">
+
+ +

Le code JavaScript de l'attribut est passé à l'objet évènement par le paramètre event. La valeur renvoyée est traitée d'une façon spéciale décrite dans la spécification HTML.

+ +

Ce moyen devrait être évité. Cela rend le balisage plus grand et moins lisible. Les aspects de contenu / structure et comportement ne sont pas bien séparés, rendant un bogue plus difficile à trouver.

+ +

Propriétés d'un élément DOM

+ +
// Supposons que myButton est un élément de bouton
+myButton.onclick = function(event){alert('Hello world');};
+
+ +

La fonction peut être définie pour prendre un paramètre d'event. La valeur renvoyée est traitée de façon spéciale décrite dans la spécification HTML.

+ +

Le problème avec cette méthode est qu'un seul gestionnaire peut être défini par élément et par évènement.

+ +

Accès aux interfaces d'évènements

+ +

Les gestionnaires d'évènements peuvent être attachés à divers objets y compris les éléments DOM, le document, l'objet fenêtre, etc. Lorsqu'un évènement se produit, un objet évènement est créé et passé séquentiellement aux écouteurs d'évènements.

+ +

L'interface {{domxref("Event")}} est accessible à partir de la fonction gestionnaire, via l'objet événement passé en premier argument. L'exemple simple suivant montre comment un objet d'événement est transmis à la fonction de gestionnaire d'événements et peut être utilisé à partir d'une telle fonction.

+ +
function foo(evt) {
+  // le paramètre evt est automatiquement assigné à l'objet évènement
+  alert(evt);
+}
+table_el.onclick = foo;
+
+ + + + diff --git a/files/fr/orphaned/web/guide/events/index.html b/files/fr/orphaned/web/guide/events/index.html new file mode 100644 index 0000000000..4ed6e68693 --- /dev/null +++ b/files/fr/orphaned/web/guide/events/index.html @@ -0,0 +1,19 @@ +--- +title: Event developer guide +slug: orphaned/Web/Guide/Events +tags: + - DOM + - Event + - Guide + - TopicStub + - events +translation_of: Web/Guide/Events +original_slug: Web/Guide/Events +--- +

{{draft()}}

+ +

Tout ce que vous devez savoir sur les événements sera présenté ici. Nous travaillons sur le nettoyage ici maintenant.

+ +

Docs

+ +

{{LandingPageListSubpages}}

diff --git a/files/fr/orphaned/web/guide/events/orientation_and_motion_data_explained/index.html b/files/fr/orphaned/web/guide/events/orientation_and_motion_data_explained/index.html new file mode 100644 index 0000000000..e0d044bfb2 --- /dev/null +++ b/files/fr/orphaned/web/guide/events/orientation_and_motion_data_explained/index.html @@ -0,0 +1,77 @@ +--- +title: Les données d'orientation et de mouvement expliquées +slug: orphaned/Web/Guide/Events/Orientation_and_motion_data_explained +tags: + - Coordonnées + - Mobile + - Mouvement + - Orientation + - rotation +translation_of: Web/Guide/Events/Orientation_and_motion_data_explained +original_slug: Web/Guide/Events/Orientation_and_motion_data_explained +--- +

{{ Draft() }}

+ +

Résumé

+ +

Lorsque vous utilisez des événements d'orientation et de mouvement, il est important de comprendre les valeurs que vous donne le navigateur. Cet article fournit des détails sur les systèmes de coordonnées en jeu et comment vous les utilisez.

+ +
+

Attention : Actuellement, Firefox et Chrome ne gèrent pas ces  coordonnées de la même manière. Prenez-y garde en les utilisant.

+
+ +

À propos des cadres de coordonnées

+ +

Un cadre de coordonnées est un système grâce auquel l'orientation des trois axes (X, Y et Z) d'un objet est définie. Il existe deux cadres de coordonnées à prendre en compte lors de l'utilisation d'événements d'orientation et de mouvement:

+ +

Le cadre de coordonnées de la Terre

+ +

Le cadre de coordonnées de la Terre est celui basé sur le centre de la Terre ; c'est-à-dire que les axes sont alignés sur la base de l'attraction de la gravité et de l'orientation nord magnétique standard. Nous utilisons des lettres majuscules ("X", "Y" et "Z") pour décrire les axes du cadre de coordonnées de la Terre.

+ +
    +
  • L'axe X  suit le plan du sol, perpendiculaire à l'axe Y, et positif vers l'est (et donc négatif vers l'ouest).
  • +
  • L'axe Y suit le plan du sol et est positif vers le vrai nord (c'est-à-dire le pôle nord, pas le nord magnétique) et négatif vers le vrai sud.
  • +
  • L'axe Z est perpendiculaire au plan du sol ; pensez-y comme une ligne tracée entre l'appareil et le centre de la Terre. La valeur de la coordonnée Z est positive vers le haut (loin du centre de la Terre) et négative vers le bas (vers le centre de la Terre).
  • +
+ +

Le cadre de coordonnées de l'appareil

+ +

Le cadre de coordonnées de l'appareil est basé sur le centre de l'appareil. Nous utilisons des lettres minuscules ("x", "y" et "z") pour décrire les axes du cadre de coordonnées de l'appareil.

+ +

axes.png

+ +
    +
  • L'axe x est dans le plan de l'écran et est positif vers la droite et négatif vers la gauche.
  • +
  • L'axe y est dans le plan de l'écran et est positif vers le haut et négatif vers le bas.
  • +
  • L'axe z est perpendiculaire à l'écran ou au clavier et positif à partir de l'écran.
  • +
+ +
Note : Sur un téléphone ou une tablette, l'orientation de l'appareil est toujours considérée par rapport à l'orientation standard de l'écran ; c'est l'orientation "portrait" sur la plupart des appareils. Sur un ordinateur portable, l'orientation est considérée par rapport au clavier. Si vous voulez détecter les changements d'orientation de l'appareil pour compenser, vous pouvez utiliser l'évènement orientationchange.
+ +

À propos de la rotation

+ +

La rotation est décrite  pour un axe donné en nombre de degrés d'écart entre le cadre de coordonnées de l'appareil et le cadre de coordonnées de la Terre, et est mesurée en degrés.

+ +

Alpha

+ +

La rotation autour de l'axe z -- c'est-à-dire, son déplacement latéral, vers la gauche ou la droite - fait changer l'angle de rotation alpha :

+ +

alpha.png

+ +

L'angle alpha est de 0° quand le haut de l'appareil pointe vers le pôle nord, et augmente lorsque l'appareil est tourné vers la gauche.

+ +

Beta

+ +

La rotation autour de l'axe x -- c'est-à-dire, l'inclinaison de l'appareil de ou vers l'utilisateur -- provoque le changement de l'angle de rotation beta :

+ +

beta.png

+ +

L'angle beta est de 0° lorsque le haut et le bas de l'appareil sont à la même distance de la surface de la Terre, et augmente vers 180 ° lorsque l'appareil est incliné vers l'avant et diminue vers -180 ° lorsque l'appareil est incliné vers l'arrière.

+ +

Gamma

+ +

La rotation autour de l'axe Y -- c'est-à-dire, l'inclinaison de l'appareil vers la gauche ou la droite -- modifie l'angle de rotation gamma :

+ +

gamma.png

+ +

L'angle gamma est de 0° lorsque les côtés gauche et droit de l'appareil sont à la même distance de la surface de la Terre et augmente vers 90 ° lorsque l'appareil est incliné vers la droite, et vers -90 ° lorsque l'appareil est incliné vers la gauche.

diff --git a/files/fr/web/api/detecting_device_orientation/index.html b/files/fr/web/api/detecting_device_orientation/index.html deleted file mode 100644 index 32d45270a1..0000000000 --- a/files/fr/web/api/detecting_device_orientation/index.html +++ /dev/null @@ -1,220 +0,0 @@ ---- -title: Détecter l'orientation de l'appareil -slug: Web/API/Detecting_device_orientation -tags: - - Device Orientation - - Firefox OS - - Mobile - - Motion - - Orientation -translation_of: Web/API/Detecting_device_orientation -original_slug: WebAPI/Detecting_device_orientation ---- -

{{SeeCompatTable}}

- -

Résumé

- -

De plus en plus d'appareils connectés à Internet sont capable de déterminer leur orientation. C'est-à-dire qu'ils peuvent fournir des données indiquant des changements dans leur orientation par rapport à la gravité. En particulier les appareils portables, comme les téléphones mobiles, peuvent utiliser cette information pour effectuer automatiquement une rotation de l'écran, afin de toujours proposer la meilleure disposition possible pour le contenu à afficher.

- -

Il existe deux événements JavaScript pour gérer l'orientation. Le premier est {{domxref("DeviceOrientationEvent")}}, qui est envoyé quand l'accéléromètre détecte un changement d'orientation de l'appareil. En recevant et en analysant les données fournies par ces événements d'orientation, il est possible de répondre de manière interactive aux changements d'orientation et d'élévation causés par les mouvements imprimés à l'appareil par l'utilisateur.

- -

Le second événement est {{ domxref("DeviceMotionEvent") }}, qui est envoyé quand un changement d’accélération est ajouté. Il est différent de {{domxref("DeviceOrientationEvent")}}, car il écoute les changements d'accélération par opposition à l'orientation. Parmi les capteurs capables de détecter {{ domxref("DeviceMotionEvent") }}, on trouve les capteurs des ordinateurs portables utilisés pour protéger des chutes les périphériques de stockage. Ils sont communément présents dans les appareils mobiles (tablettes, téléphones intelligents).

- -

Traitement des événements d'orientation

- -

Tout ce dont vous avez besoin pour commencer à recevoir les changements d'orientation est d’écouter l’événement {{ event("deviceorientation") }} :

- -
-

Note: gyronorm.js est un polyfill pour normaliser les données de l'accéléromètre et du gyroscope sur les appareils mobiles. C'est utile pour surmonter certaines différences dans la prise en charge des périphériques pour l'orientation du périphérique.

-
- -
window.addEventListener("deviceorientation", handleOrientation, true);
-
- -

Après l’enregistrement de votre gestionnaire d'événements (event listener en anglais), dans ce cas, une fonction JS appelée handleOrientation(), votre fonction d'écoute est appelée périodiquement pour récupérer les données de l'orientation mise à jour.

- -

L'événement d'orientation contient quatre valeurs ::

- -
    -
  • {{domxref("DeviceOrientationEvent.absolute")}}
  • -
  • {{domxref("DeviceOrientationEvent.alpha")}}
  • -
  • {{domxref("DeviceOrientationEvent.beta")}}
  • -
  • {{domxref("DeviceOrientationEvent.gamma")}}
  • -
- -

La fonction gérant l’événement pourrait ressembler à ceci :

- -
function handleOrientation(event) {
-  var absolute = event.absolute;
-  var alpha    = event.alpha;
-  var beta     = event.beta;
-  var gamma    = event.gamma;
-
-  // Faites quelque chose avec les données acquises. ;)
-}
-
- -

Détail des valeurs d'orientation

- -

La valeur reportée pour chaque axe indique l'angle de rotation autour d'un axe donné, en référence à un système de coordonnées standard. Ces valeurs sont décrites de façon plus détaillée dans cet article Orientation et déplacement expliquée.

- -
    -
  • La valeur {{ domxref("DeviceOrientationEvent.alpha") }} représente le mouvement de l'appareil, autour de l'axe « z », en degrés sur une échelle de 0° à 360° ;
  • -
  • La valeur {{ domxref("DeviceOrientationEvent.beta") }} représente le mouvement de l'appareil autour de l'axe « y » en degrés, sur une échelle de -180° à 180°.  Cela représente le mouvement d'avant en arrière de l'appareil ;
  • -
  • La valeur {{ domxref("DeviceOrientationEvent.gamma") }} représente le mouvement de l'appareil autour de l'axe « x », exprimée en degrés sur une échelle de -90° à 90°. Cela représente le mouvement de gauche à droite de l'appareil.
  • -
- -

Exemple d'orientation

- -

Cet exemple fonctionne sur tout navigateur supportant l’événement {{event("deviceorientation")}} et sur tout appareil capable de détecter son orientation.

- -

Imaginons une balle dans un jardin :

- -
<div class="jardin">
-  <div class="balle"></div>
-</div>
-
-<pre class="resultat"></pre>
-
- -

Ce jardin fait 200 pixels de long (Oui c'est un « petit » jardin !), et la balle est au centre :

- -
.jardin {
-  position: relative;
-  width : 200px;
-  height: 200px;
-  border: 5px solid #CCC;
-  border-radius: 10px;
-}
-
-.balle {
-  position: absolute;
-  top   : 90px;
-  left  : 90px;
-  width : 20px;
-  height: 20px;
-  background: green;
-  border-radius: 100%;
-}
-
- -

Maintenant, on définit le déplacement de la balle en fonction de celui de l'appareil :

- -
var jardin = document.querySelector('.jardin'),
-    balle = document.querySelector('.balle'),
-    resultat = document.querySelector('.resultat'),
-    maxX = jardin.clientWidth  - balle.clientWidth,
-    maxY = jardin.clientHeight - balle.clientHeight;
-
-function handleOrientation(event) {
-  var x = event.beta,  // En degré sur l'interval [-180,180].
-      y = event.gamma; // En degré sur l'interval [-90,90].
-
-  resultat.innerHTML  = "beta : " + x + "<br />";
-  resultat.innerHTML += "gamma: " + y + "<br />";
-
-  // Parce-que l'on ne veut pas avoir l'appareil à l'envers.
-  // On restreint les valeurs de x à l'intervalle [-90,90].
-  if (x >  90) { x =  90};
-  if (x < -90) { x = -90};
-  // Pour rendre le calcul plus simple.
-  // On délimite l'intervalle de x et y sur [0, 180].
-  x += 90;
-  y += 90;
-
-  // 10 est la moitié de la taille de la balle.
-  // Cela centre le point de positionnement au centre de la balle.
-
-  balle.style.top  = (maxX * x / 180 - 10) + "px";
-  balle.style.left = (maxY * y / 180 - 10) + "px";
-}
-
-window.addEventListener('deviceorientation', handleOrientation);
-
- -

Et voici le résultat en temps réel :

- -
{{EmbedLiveSample("Exemple_d'orientation", '230', '260')}}
- -
 
- -
{{LiveSampleLink("Exemple_d'orientation", "Cliquez ici")}} pour ouvrir cet exemple dans une nouvelle fenêtre;  l'événement {{event("deviceorientation")}} ne marche pas dans les {{HTMLElement("iframe", "iframes")}} cross-origin dans tous les navigateurs.
- -
 
- -
-

Attention : Chrome et Firefox ne gèrent pas les angles de la même façon, certaines directions sur les axes sont inversées.

-
- -

Traiter les événement de mouvement

- -

Les événements de mouvement gèrent l'orientation de la même façon à l'exception près qu’ils portent un nom d’événement différent : {{event("devicemotion")}}

- -
window.addEventListener("devicemotion", handleMotion, true);
-
- -

Ce qui change réellement est l'information fournie par l'objet {{ domxref("DeviceMotionEvent") }} passée comme paramètre par la fonction HandleMotion.

- -

Les événements de mouvement contiennent quatre propriétés :

- -
    -
  • {{domxref("DeviceMotionEvent.acceleration")}}
  • -
  • {{domxref("DeviceMotionEvent.accelerationIncludingGravity")}}
  • -
  • {{domxref("DeviceMotionEvent.rotationRate")}}
  • -
  • {{domxref("DeviceMotionEvent.interval")}}
  • -
- -

Explication des valeurs de mouvement

- -

L'objet {{ domxref("DeviceMotionEvent") }} fourni aux développeurs Web des informations sur la vitesse de changement d'orientation et de position de l'appareil. Les changements rapportés sont fournis pour les trois axes (voir Orientation et déplacement expliquées pour les détails).

- -

Pour {{domxref("DeviceMotionEvent.acceleration","acceleration")}} et {{domxref("DeviceMotionEvent.accelerationIncludingGravity","accelerationIncludingGravity")}}, Les axes correspondent à :

- -
    -
  • x : représente l'axe d'Ouest en Est ;
  • -
  • y : représente l'axe Sud vers Nord :
  • -
  • z : représente l'axe perpendiculaire au sol.
  • -
- -

Pour {{domxref("DeviceMotionEvent.rotationRate","rotationRate")}}, c'est un peu différent. L'information correspond à :

- -
    -
  • alpha : représente le ratio de rotation le long de l'axe perpendiculaire à l'écran (ou du clavier au bureau) ;
  • -
  • bêta : représente le ratio de rotation le long de l'axe allant de la gauche vers la droite de l'écran (ou du clavier au bureau) ;
  • -
  • gamma : représente le ratio de rotation le long de l'axe allant du bas vers le haut de l'écran (ou clavier vers le bureau).
  • -
- -

Au final, {{domxref("DeviceMotionEvent.interval","interval")}} représente l'intervalle de temps, en millisecondes, pour les données générées par l'appareil.

- -

Spécifications

- - - - - - - - - - - - - - - - -
SpécificationStatutCommentaires
{{SpecName('Device Orientation')}}{{Spec2('Device Orientation')}}Spécification initiale.
- -

Compatibilité des navigateurs

- -

{{Compat("api.DeviceOrientationEvent")}}

- -

Voir aussi

- - diff --git a/files/fr/web/api/document_object_model/events/index.html b/files/fr/web/api/document_object_model/events/index.html deleted file mode 100644 index 053a61a2dc..0000000000 --- a/files/fr/web/api/document_object_model/events/index.html +++ /dev/null @@ -1,75 +0,0 @@ ---- -title: Les évènements et le DOM -slug: Web/API/Document_Object_Model/Events -tags: - - API - - DOM - - Guide - - évènements -translation_of: Web/API/Document_Object_Model/Events -original_slug: Web/API/Document_Object_Model/Les_évènements_et_le_DOM ---- -

Introduction

- -

Ce chapitre décrit le modèle d'événement DOM. L'interface Event elle-même est décrite, ainsi que les interfaces pour l'enregistrement des évènements sur les noeuds dans le DOM, les écouteurs d'évènements et d'autres exemples montrant les relations des différentes interfaces d'évènements entre elles.

- -

Il existe un excellent diagramme qui explique clairement les trois phases du flux d'évènements à travers le DOM dans le document sur les évènements DOM Niveau 3.

- -

Voir aussi l'exemple 5 : Propagation des évènements dans le chapitre "Exemples" pour des exemples détaillés sur le déplacement des évènements à travers le DOM.

- -

Enregistrement des écouteurs d'évènements

- -

Il y a 3 moyens d'enregistrer les gestionnaires d'évènements pour un élément DOM.

- -

EventTarget.addEventListener

- -
// Supposons que myButton est un élément de bouton
-myButton.addEventListener('click', function(){alert('Hello world');}, false);
-
- -

C'est la méthode à utiliser dans les pages web modernes.

- -

Note : Internet Explorer 6-8 ne prend pas en charge cette méthode, il offre une API similaire {{domxref("EventTarget.attachEvent")}} à la place. Pour la compatibilité entre navigateurs, utilisez l'une des nombreuses bibliothèques JavaScript disponibles.

- -

Plus de détails peuvent être trouvés sur la page de référence {{domxref("EventTarget.addEventListener")}}.

- -

attribut HTML

- -
<button onclick="alert('Hello world!')">
-
- -

Le code JavaScript de l'attribut est passé à l'objet évènement par le paramètre event. La valeur renvoyée est traitée d'une façon spéciale décrite dans la spécification HTML.

- -

Ce moyen devrait être évité. Cela rend le balisage plus grand et moins lisible. Les aspects de contenu / structure et comportement ne sont pas bien séparés, rendant un bogue plus difficile à trouver.

- -

Propriétés d'un élément DOM

- -
// Supposons que myButton est un élément de bouton
-myButton.onclick = function(event){alert('Hello world');};
-
- -

La fonction peut être définie pour prendre un paramètre d'event. La valeur renvoyée est traitée de façon spéciale décrite dans la spécification HTML.

- -

Le problème avec cette méthode est qu'un seul gestionnaire peut être défini par élément et par évènement.

- -

Accès aux interfaces d'évènements

- -

Les gestionnaires d'évènements peuvent être attachés à divers objets y compris les éléments DOM, le document, l'objet fenêtre, etc. Lorsqu'un évènement se produit, un objet évènement est créé et passé séquentiellement aux écouteurs d'évènements.

- -

L'interface {{domxref("Event")}} est accessible à partir de la fonction gestionnaire, via l'objet événement passé en premier argument. L'exemple simple suivant montre comment un objet d'événement est transmis à la fonction de gestionnaire d'événements et peut être utilisé à partir d'une telle fonction.

- -
function foo(evt) {
-  // le paramètre evt est automatiquement assigné à l'objet évènement
-  alert(evt);
-}
-table_el.onclick = foo;
-
- - - - diff --git a/files/fr/web/guide/events/index.html b/files/fr/web/guide/events/index.html deleted file mode 100644 index 79b85e1372..0000000000 --- a/files/fr/web/guide/events/index.html +++ /dev/null @@ -1,19 +0,0 @@ ---- -title: Event developer guide -slug: Web/Guide/Events -tags: - - DOM - - Event - - Guide - - TopicStub - - events -translation_of: Web/Guide/Events -original_slug: Web/Guide/DOM/Events ---- -

{{draft()}}

- -

Tout ce que vous devez savoir sur les événements sera présenté ici. Nous travaillons sur le nettoyage ici maintenant.

- -

Docs

- -

{{LandingPageListSubpages}}

diff --git a/files/fr/web/guide/events/orientation_and_motion_data_explained/index.html b/files/fr/web/guide/events/orientation_and_motion_data_explained/index.html deleted file mode 100644 index d6b0145e3e..0000000000 --- a/files/fr/web/guide/events/orientation_and_motion_data_explained/index.html +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: Les données d'orientation et de mouvement expliquées -slug: Web/Guide/Events/Orientation_and_motion_data_explained -tags: - - Coordonnées - - Mobile - - Mouvement - - Orientation - - rotation -translation_of: Web/Guide/Events/Orientation_and_motion_data_explained -original_slug: Web/Guide/DOM/Events/Les_données_d_orientation_et_de_mouvement_expliquées ---- -

{{ Draft() }}

- -

Résumé

- -

Lorsque vous utilisez des événements d'orientation et de mouvement, il est important de comprendre les valeurs que vous donne le navigateur. Cet article fournit des détails sur les systèmes de coordonnées en jeu et comment vous les utilisez.

- -
-

Attention : Actuellement, Firefox et Chrome ne gèrent pas ces  coordonnées de la même manière. Prenez-y garde en les utilisant.

-
- -

À propos des cadres de coordonnées

- -

Un cadre de coordonnées est un système grâce auquel l'orientation des trois axes (X, Y et Z) d'un objet est définie. Il existe deux cadres de coordonnées à prendre en compte lors de l'utilisation d'événements d'orientation et de mouvement:

- -

Le cadre de coordonnées de la Terre

- -

Le cadre de coordonnées de la Terre est celui basé sur le centre de la Terre ; c'est-à-dire que les axes sont alignés sur la base de l'attraction de la gravité et de l'orientation nord magnétique standard. Nous utilisons des lettres majuscules ("X", "Y" et "Z") pour décrire les axes du cadre de coordonnées de la Terre.

- -
    -
  • L'axe X  suit le plan du sol, perpendiculaire à l'axe Y, et positif vers l'est (et donc négatif vers l'ouest).
  • -
  • L'axe Y suit le plan du sol et est positif vers le vrai nord (c'est-à-dire le pôle nord, pas le nord magnétique) et négatif vers le vrai sud.
  • -
  • L'axe Z est perpendiculaire au plan du sol ; pensez-y comme une ligne tracée entre l'appareil et le centre de la Terre. La valeur de la coordonnée Z est positive vers le haut (loin du centre de la Terre) et négative vers le bas (vers le centre de la Terre).
  • -
- -

Le cadre de coordonnées de l'appareil

- -

Le cadre de coordonnées de l'appareil est basé sur le centre de l'appareil. Nous utilisons des lettres minuscules ("x", "y" et "z") pour décrire les axes du cadre de coordonnées de l'appareil.

- -

axes.png

- -
    -
  • L'axe x est dans le plan de l'écran et est positif vers la droite et négatif vers la gauche.
  • -
  • L'axe y est dans le plan de l'écran et est positif vers le haut et négatif vers le bas.
  • -
  • L'axe z est perpendiculaire à l'écran ou au clavier et positif à partir de l'écran.
  • -
- -
Note : Sur un téléphone ou une tablette, l'orientation de l'appareil est toujours considérée par rapport à l'orientation standard de l'écran ; c'est l'orientation "portrait" sur la plupart des appareils. Sur un ordinateur portable, l'orientation est considérée par rapport au clavier. Si vous voulez détecter les changements d'orientation de l'appareil pour compenser, vous pouvez utiliser l'évènement orientationchange.
- -

À propos de la rotation

- -

La rotation est décrite  pour un axe donné en nombre de degrés d'écart entre le cadre de coordonnées de l'appareil et le cadre de coordonnées de la Terre, et est mesurée en degrés.

- -

Alpha

- -

La rotation autour de l'axe z -- c'est-à-dire, son déplacement latéral, vers la gauche ou la droite - fait changer l'angle de rotation alpha :

- -

alpha.png

- -

L'angle alpha est de 0° quand le haut de l'appareil pointe vers le pôle nord, et augmente lorsque l'appareil est tourné vers la gauche.

- -

Beta

- -

La rotation autour de l'axe x -- c'est-à-dire, l'inclinaison de l'appareil de ou vers l'utilisateur -- provoque le changement de l'angle de rotation beta :

- -

beta.png

- -

L'angle beta est de 0° lorsque le haut et le bas de l'appareil sont à la même distance de la surface de la Terre, et augmente vers 180 ° lorsque l'appareil est incliné vers l'avant et diminue vers -180 ° lorsque l'appareil est incliné vers l'arrière.

- -

Gamma

- -

La rotation autour de l'axe Y -- c'est-à-dire, l'inclinaison de l'appareil vers la gauche ou la droite -- modifie l'angle de rotation gamma :

- -

gamma.png

- -

L'angle gamma est de 0° lorsque les côtés gauche et droit de l'appareil sont à la même distance de la surface de la Terre et augmente vers 90 ° lorsque l'appareil est incliné vers la droite, et vers -90 ° lorsque l'appareil est incliné vers la gauche.

diff --git a/files/ja/_redirects.txt b/files/ja/_redirects.txt index 093e37fee3..7c9273da6e 100644 --- a/files/ja/_redirects.txt +++ b/files/ja/_redirects.txt @@ -1280,7 +1280,7 @@ /ja/docs/DOM/DOMString /ja/docs/Web/API/DOMString /ja/docs/DOM/DOMTimeStamp /ja/docs/Web/API/DOMTimeStamp /ja/docs/DOM/DOM_Reference /ja/docs/Web/API/Document_Object_Model -/ja/docs/DOM/DOM_Reference/Events /ja/docs/Web/API/Document_Object_Model/Events +/ja/docs/DOM/DOM_Reference/Events /ja/docs/orphaned/Web/API/Document_Object_Model/Events /ja/docs/DOM/DOM_Reference/Examples /ja/docs/Web/API/Document_Object_Model/Examples /ja/docs/DOM/DOM_Reference/Introduction /ja/docs/Web/API/Document_Object_Model/Introduction /ja/docs/DOM/DOM_Reference/Preface /ja/docs/conflicting/Web/API/Document_Object_Model_8435a25d5137b436d5d7161e1b813c02 @@ -1385,7 +1385,7 @@ /ja/docs/DOM/NodeIterator /ja/docs/Web/API/NodeIterator /ja/docs/DOM/NodeList /ja/docs/Web/API/NodeList /ja/docs/DOM/NodeList.item /ja/docs/Web/API/NodeList/item -/ja/docs/DOM/Orientation_and_motion_data_explained /ja/docs/Web/Guide/Events/Orientation_and_motion_data_explained +/ja/docs/DOM/Orientation_and_motion_data_explained /ja/docs/orphaned/Web/Guide/Events/Orientation_and_motion_data_explained /ja/docs/DOM/Plugin /ja/docs/Web/API/Plugin /ja/docs/DOM/PluginArray /ja/docs/Web/API/PluginArray /ja/docs/DOM/SVGFontElement /ja/docs/Web/API/SVGFontElement @@ -1993,7 +1993,7 @@ /ja/docs/DebNews /ja/docs/orphaned/DebNews /ja/docs/DebNews/20081118 /ja/docs/orphaned/DevNews/20081118 /ja/docs/Deer_Park /ja/docs/Mozilla/Firefox/Releases/1.5 -/ja/docs/Detecting_device_orientation /ja/docs/Web/API/Detecting_device_orientation +/ja/docs/Detecting_device_orientation /ja/docs/orphaned/Web/API/Detecting_device_orientation /ja/docs/Determining_the_dimensions_of_elements /ja/docs/conflicting/Web/API/CSS_Object_Model/Determining_the_dimensions_of_elements /ja/docs/DevNews /ja/docs/orphaned/DevNews /ja/docs/DevNews/20060705 /ja/docs/orphaned/DevNews/20060705 @@ -3742,6 +3742,7 @@ /ja/docs/Web/API/Coordinates /ja/docs/Web/API/GeolocationCoordinates /ja/docs/Web/API/DOMCursor.done /ja/docs/Web/API/DOMCursor/done /ja/docs/Web/API/DOMRequest.error /ja/docs/Web/API/DOMRequest/error +/ja/docs/Web/API/Detecting_device_orientation /ja/docs/orphaned/Web/API/Detecting_device_orientation /ja/docs/Web/API/DeviceAcceleration /ja/docs/Web/API/DeviceMotionEventAcceleration /ja/docs/Web/API/DeviceLightEvent.value /ja/docs/Web/API/DeviceLightEvent/value /ja/docs/Web/API/Document.domConfig /ja/docs/Web/API/Document @@ -3763,6 +3764,7 @@ /ja/docs/Web/API/DocumentOrShadowRoot/nodesFromPoint /ja/docs/conflicting/Web/API/DocumentOrShadowRoot_20ea0e1d91453a020aad3a16dbce16f1 /ja/docs/Web/API/DocumentOrShadowRoot/pointerLockElement /ja/docs/Web/API/Document/pointerLockElement /ja/docs/Web/API/DocumentOrShadowRoot/styleSheets /ja/docs/Web/API/Document/styleSheets +/ja/docs/Web/API/Document_Object_Model/Events /ja/docs/orphaned/Web/API/Document_Object_Model/Events /ja/docs/Web/API/Document_Object_Model/Preface /ja/docs/conflicting/Web/API/Document_Object_Model_8435a25d5137b436d5d7161e1b813c02 /ja/docs/Web/API/Element.contentEditable /ja/docs/Web/API/HTMLElement/contentEditable /ja/docs/Web/API/Element.isContentEditable /ja/docs/Web/API/HTMLElement/isContentEditable @@ -3773,7 +3775,7 @@ /ja/docs/Web/API/Element/name /ja/docs/conflicting/Web/API /ja/docs/Web/API/Event/button /ja/docs/conflicting/Web/API/MouseEvent/button /ja/docs/Web/API/Event/createEvent /ja/docs/conflicting/Web/API/Document/createEvent -/ja/docs/Web/API/EventHandler /ja/docs/Web/Guide/Events/Event_handlers +/ja/docs/Web/API/EventHandler /ja/docs/orphaned/Web/Guide/Events/Event_handlers /ja/docs/Web/API/EventTarget.addEventListener /ja/docs/Web/API/EventTarget/addEventListener /ja/docs/Web/API/EventTarget.dispatchEvent /ja/docs/Web/API/EventTarget/dispatchEvent /ja/docs/Web/API/EventTarget.removeEventListener /ja/docs/Web/API/EventTarget/removeEventListener @@ -4573,7 +4575,11 @@ /ja/docs/Web/Guide/DOM/Manipulating_the_browser_history/Working_with_the_History_API /ja/docs/Web/API/History_API/Working_with_the_History_API /ja/docs/Web/Guide/DOM/Using_full_screen_mode /ja/docs/Web/API/Fullscreen_API /ja/docs/Web/Guide/DOM/Whitespace_in_the_DOM /ja/docs/Web/API/Document_Object_Model/Whitespace +/ja/docs/Web/Guide/Events /ja/docs/orphaned/Web/Guide/Events /ja/docs/Web/Guide/Events/Creating_and_triggering_events /ja/docs/orphaned/Web/Guide/Events/Creating_and_triggering_events +/ja/docs/Web/Guide/Events/Event_handlers /ja/docs/orphaned/Web/Guide/Events/Event_handlers +/ja/docs/Web/Guide/Events/Orientation_and_motion_data_explained /ja/docs/orphaned/Web/Guide/Events/Orientation_and_motion_data_explained +/ja/docs/Web/Guide/Events/Overview_of_Events_and_Handlers /ja/docs/orphaned/Web/Guide/Events/Overview_of_Events_and_Handlers /ja/docs/Web/Guide/Graphics/Drawing_graphics_with_canvas /ja/docs/conflicting/Web/API/Canvas_API/Tutorial_3cd5468edc15a1ef1ddc0d2b17e1fa5d /ja/docs/Web/Guide/HTML /ja/docs/Learn/HTML /ja/docs/Web/Guide/HTML/Canvas_tutorial /ja/docs/conflicting/Web/API/Canvas_API/Tutorial diff --git a/files/ja/_wikihistory.json b/files/ja/_wikihistory.json index c8a29de950..0a54926ffe 100644 --- a/files/ja/_wikihistory.json +++ b/files/ja/_wikihistory.json @@ -11424,15 +11424,6 @@ "chikoski" ] }, - "Web/API/Detecting_device_orientation": { - "modified": "2020-10-15T21:21:30.973Z", - "contributors": [ - "YujiSoftware", - "hamasaki", - "yyss", - "Fajrovulpo" - ] - }, "Web/API/DeviceLightEvent": { "modified": "2020-10-15T21:33:03.860Z", "contributors": [ @@ -12749,15 +12740,6 @@ "Okome" ] }, - "Web/API/Document_Object_Model/Events": { - "modified": "2020-09-27T12:30:54.835Z", - "contributors": [ - "mfuji09", - "dskmori", - "keeponbeat", - "mikamikuh" - ] - }, "Web/API/Document_Object_Model/Examples": { "modified": "2019-06-14T18:12:08.377Z", "contributors": [ @@ -32695,35 +32677,6 @@ "ethertank" ] }, - "Web/Guide/Events": { - "modified": "2019-03-18T20:59:28.336Z", - "contributors": [ - "mfuji09", - "gportioli" - ] - }, - "Web/Guide/Events/Event_handlers": { - "modified": "2020-08-30T04:00:41.655Z", - "contributors": [ - "mfuji09", - "k-kuwahara", - "silverskyvicto", - "momdo" - ] - }, - "Web/Guide/Events/Orientation_and_motion_data_explained": { - "modified": "2020-07-25T12:40:06.161Z", - "contributors": [ - "mfuji09", - "yyss" - ] - }, - "Web/Guide/Events/Overview_of_Events_and_Handlers": { - "modified": "2019-03-18T21:46:16.505Z", - "contributors": [ - "superyusuke" - ] - }, "Web/Guide/Graphics": { "modified": "2019-10-11T10:49:15.066Z", "contributors": [ @@ -53496,5 +53449,52 @@ "y4m4to", "lv7777" ] + }, + "orphaned/Web/API/Detecting_device_orientation": { + "modified": "2020-10-15T21:21:30.973Z", + "contributors": [ + "YujiSoftware", + "hamasaki", + "yyss", + "Fajrovulpo" + ] + }, + "orphaned/Web/API/Document_Object_Model/Events": { + "modified": "2020-09-27T12:30:54.835Z", + "contributors": [ + "mfuji09", + "dskmori", + "keeponbeat", + "mikamikuh" + ] + }, + "orphaned/Web/Guide/Events/Event_handlers": { + "modified": "2020-08-30T04:00:41.655Z", + "contributors": [ + "mfuji09", + "k-kuwahara", + "silverskyvicto", + "momdo" + ] + }, + "orphaned/Web/Guide/Events": { + "modified": "2019-03-18T20:59:28.336Z", + "contributors": [ + "mfuji09", + "gportioli" + ] + }, + "orphaned/Web/Guide/Events/Orientation_and_motion_data_explained": { + "modified": "2020-07-25T12:40:06.161Z", + "contributors": [ + "mfuji09", + "yyss" + ] + }, + "orphaned/Web/Guide/Events/Overview_of_Events_and_Handlers": { + "modified": "2019-03-18T21:46:16.505Z", + "contributors": [ + "superyusuke" + ] } } \ No newline at end of file diff --git a/files/ja/orphaned/web/api/detecting_device_orientation/index.html b/files/ja/orphaned/web/api/detecting_device_orientation/index.html new file mode 100644 index 0000000000..484067e66f --- /dev/null +++ b/files/ja/orphaned/web/api/detecting_device_orientation/index.html @@ -0,0 +1,229 @@ +--- +title: デバイスの方向の検出 +slug: orphaned/Web/API/Detecting_device_orientation +tags: + - API + - Device Orientation + - Firefox OS + - Intermediate + - Mobile + - Motion + - Orientation + - Reference + - WebAPI +translation_of: Web/API/Detecting_device_orientation +original_slug: Web/API/Detecting_device_orientation +--- +
{{SeeCompatTable}}
+ +

Web を利用可能なデバイスは、自身の方向を特定できるようになってきました。つまりデバイスは、重力との関係による自身の向きの変化を示すデータを報告できます。特に携帯電話のようなハンドヘルドデバイスは、表示内容が直立し続けるよう自動的に回転させるためにこの情報を使用でき、画面の幅が高さより大きくなるようにデバイスを回転させたときは、Web コンテンツをワイドスクリーン表示にします。

+ +

方向の情報を制御する JavaScript イベントが 2 つあります。ひとつは {{domxref("DeviceOrientationEvent")}} であり、加速度センサーがデバイスの方向の変化を検出したときに発生します。Orientation イベントが報告するデータを受け取って処理することで、ユーザがデバイスを動かすことによる方向や高さの変化に対してインタラクティブに応答できるようになります。

+ +

もうひとつのイベントは {{domxref("DeviceMotionEvent")}} であり、加速度が変化したときに発生します。こちらは方向ではなく加速度の変化を監視することが、{{domxref("DeviceOrientationEvent")}} との違いです。一般的に {{domxref("DeviceMotionEvent")}} を検出できるセンサーには、可動部があるストレージ装置を保護するためラップトップパソコンに内蔵するものも含みます。{{domxref("DeviceOrientationEvent")}} は、モバイルデバイスでとても一般的です。

+ +

orientation イベントを処理する

+ +

方向の変化を受け取り始めるには、{{event("deviceorientation")}} イベントをリッスンします:

+ +
+

注記: gyronorm.js は、モバイルデバイスの加速度センサーやジャイロスコープのデータを正規化するためのポリフィルです。これは、デバイスの方向のサポート状況の違いを克服するのに役立ちます。

+
+ +
window.addEventListener("deviceorientation", handleOrientation, true);
+
+ +

イベントリスナ (この例では handleOrientation() という名前の JavaScript 関数) を登録すると、リスナ関数は最新の方向データとともに、周期的に呼び出されます。

+ +

Orientation イベントは 4 つの値を持ちます:

+ +
    +
  • {{domxref("DeviceOrientationEvent.absolute")}}
  • +
  • {{domxref("DeviceOrientationEvent.alpha")}}
  • +
  • {{domxref("DeviceOrientationEvent.beta")}}
  • +
  • {{domxref("DeviceOrientationEvent.gamma")}}
  • +
+ +

イベントハンドラ関数は以下のようなものです:

+ +
function handleOrientation(event) {
+  var absolute = event.absolute;
+  var alpha    = event.alpha;
+  var beta     = event.beta;
+  var gamma    = event.gamma;
+
+  // 新たな方向データに基づいて処理を行う
+}
+
+ +

方向として示される値

+ +

それぞれの軸で報告される値は、標準座標系の軸を中心にした回転量を表します。これらは方向および動きとして示されるデータの記事で詳しく説明しており、ここでは概要を記載します。

+ +
    +
  • {{domxref("DeviceOrientationEvent.alpha")}} の値は z 軸を中心にしたデバイスの動きを表し、0 から 360 の範囲による度数で表されます。
  • +
  • {{domxref("DeviceOrientationEvent.beta")}} の値は x 軸を中心にしたデバイスの動きを表し、-180 から 180 の範囲の値による度数で表されます。これはデバイスの前後の動きです。
  • +
  • {{domxref("DeviceOrientationEvent.gamma")}} の値は y 軸を中心にしたデバイスの動きを表し、-90 から 90 の範囲の値による度数で表されます。これはデバイスの左右の動きです。
  • +
+ +

+ +

このサンプルは方向を検出可能なデバイス上で、{{event("deviceorientation")}} イベントをサポートするブラウザを実行する場合に動作します。

+ +

庭にボールがあると考えます:

+ +
<div class="garden">
+  <div class="ball"></div>
+</div>
+
+<pre class="output"></pre>
+
+ +

庭の幅は 200 ピクセルであり (小さな庭です)、ボールは中心にあります:

+ +
.garden {
+  position: relative;
+  width : 200px;
+  height: 200px;
+  border: 5px solid #CCC;
+  border-radius: 10px;
+}
+
+.ball {
+  position: absolute;
+  top   : 90px;
+  left  : 90px;
+  width : 20px;
+  height: 20px;
+  background: green;
+  border-radius: 100%;
+}
+
+ +

デバイスを動かすと、その動きに応じてボールが移動します:

+ +
var ball   = document.querySelector('.ball');
+var garden = document.querySelector('.garden');
+var output = document.querySelector('.output');
+
+var maxX = garden.clientWidth  - ball.clientWidth;
+var maxY = garden.clientHeight - ball.clientHeight;
+
+function handleOrientation(event) {
+  var x = event.beta;  // -180 から 180 の範囲で角度を示す
+  var y = event.gamma; // -90 から 90 の範囲で角度を示す
+
+  output.innerHTML  = "beta : " + x + "\n";
+  output.innerHTML += "gamma: " + y + "\n";
+
+  // デバイスをひっくり返したくはないため、
+  // x の値を -90 から 90 の範囲に制限する
+  if (x >  90) { x =  90};
+  if (x < -90) { x = -90};
+
+  // 計算を容易にするため、x および y の値の範囲を
+  // 0 から 180 に変換する
+  x += 90;
+  y += 90;
+
+  // 10 は、ボールのサイズの半分である。
+  // これにより、配置場所をボールの中心に合わせる
+  ball.style.top  = (maxX*x/180 - 10) + "px";
+  ball.style.left = (maxY*y/180 - 10) + "px";
+}
+
+window.addEventListener('deviceorientation', handleOrientation);
+
+ +

結果を以下に示します:

+ +
{{EmbedLiveSample('Orientation_example', '230', '260')}}
+ +
+

警告: Chrome と Firefox では角度の扱い方が異なり、一部の軸の向きが逆になっています。

+
+ +

motion イベントを処理する

+ +

motion イベントは orientation イベントと同じ方法で扱えますが、イベント名は {{event("devicemotion")}} になります。

+ +
window.addEventListener("devicemotion", handleMotion, true);
+ +

実際どのように変化したかの情報は、HandleMotion 関数のパラメータとして渡す {{domxref("DeviceMotionEvent")}} オブジェクトが提供します。

+ +

motion イベントは 4 つのプロパティを持ちます:

+ +
    +
  • {{domxref("DeviceMotionEvent.acceleration")}}
  • +
  • {{domxref("DeviceMotionEvent.accelerationIncludingGravity")}}
  • +
  • {{domxref("DeviceMotionEvent.rotationRate")}}
  • +
  • {{domxref("DeviceMotionEvent.interval")}}
  • +
+ +

動きとして示される値

+ +

{{domxref("DeviceMotionEvent")}} オブジェクトは Web 開発者に、デバイスの位置や方向が変化した速度の情報を提供します。変化量は 3 つの軸 (詳しくは方向および動きとして示されるデータをご覧ください) に沿って表します。

+ +

{{domxref("DeviceMotionEvent.acceleration","acceleration")}} および {{domxref("DeviceMotionEvent.accelerationIncludingGravity","accelerationIncludingGravity")}} で対応する軸は以下のとおりです:

+ +
    +
  • x: 西から東へ向かう軸を表します。
  • +
  • y: 南から北へ向かう軸を表します。
  • +
  • z: 地面から直立する軸を表します。
  • +
+ +

{{domxref("DeviceMotionEvent.rotationRate","rotationRate")}} では状況が若干異なります。こちらの情報はそれぞれ以下のように対応します:

+ +
    +
  • alpha: スクリーン (デスクトップ環境ではキーボード) から直立する軸を表します。
  • +
  • beta: スクリーンの面 (デスクトップ環境ではキーボード) の左から右へ向かう軸に沿った回転量を表します。
  • +
  • gamma: スクリーンの面 (デスクトップ環境ではキーボード) の下から上へ向かう軸に沿った回転量を表します。
  • +
+ +

最後に {{domxref("DeviceMotionEvent.interval","interval")}} は、デバイスからデータを取得する間隔をミリ秒単位で表します。

+ +

仕様

+ + + + + + + + + + + + + + + + +
仕様書策定状況コメント
{{SpecName('Device Orientation')}}{{Spec2('Device Orientation')}}最初の仕様
+ +

ブラウザ実装状況

+ +
+

DeviceMotionEvent

+ + + +

{{Compat("api.DeviceMotionEvent")}}

+ +

DeviceOrientationEvent

+ + + +

{{Compat("api.DeviceOrientationEvent")}}

+
+ +

関連情報

+ + diff --git a/files/ja/orphaned/web/api/document_object_model/events/index.html b/files/ja/orphaned/web/api/document_object_model/events/index.html new file mode 100644 index 0000000000..7443168f11 --- /dev/null +++ b/files/ja/orphaned/web/api/document_object_model/events/index.html @@ -0,0 +1,89 @@ +--- +title: イベントと DOM +slug: orphaned/Web/API/Document_Object_Model/Events +tags: + - DOM + - Guide + - ガイド +translation_of: Web/API/Document_Object_Model/Events +original_slug: Web/API/Document_Object_Model/Events +--- +
{{DefaultAPISidebar("DOM")}}
+ +

はじめに

+ +

この章では DOM のイベントモデルを説明します。この Event インターフェイス自身は、 DOM のノード上にイベントを登録する為のインターフェイスと同様であり、イベントリスナーであるとも言えます。いくつかの長い例は、様々な Event インターフェイスがどのように他と関連するかを示します。

+ +

DOM レベル 3 イベントの原案に、DOM を通して 3 つのフェーズから構成されるイベントフローを明確に説明した素晴らしい説明図があります。

+ +

また、イベントが DOM 内をどのように伝播するかについては更に詳細なコード例、例 5: イベント伝播 (propagation) を参照してください。

+ +

イベントリスナーの登録

+ +

DOM の要素にイベントハンドラーを登録する方法は 3 つあります。

+ +

{{domxref("EventTarget.addEventListener")}}

+ +
// myButton は button 要素だと仮定します
+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')
+}
+
+ +

これが最近のウェブページで使われる方法です。

+ +
+

注: Internet Explorer 6 から 8 はこの方法をサポートせず、 {{domxref("EventTarget.attachEvent")}} という似た API を代わりにサポートします。ブラウザー間の互換性を確保するには、数多くある JavaScript ライブラリのうちの一つを使用してください。

+
+ +

さらに詳細を知りたい場合は {{domxref("EventTarget.addEventListener")}} のリファレンスを参照してください。

+ +

HTML 属性

+ +
<button onclick="alert('Hello world!')">
+
+ +

HTML 属性に書かれたこの JavaScript コードには、 event 引数を通してイベントオブジェクトが渡されます。返値は HTML の仕様で定義された特別な方法で処理されます

+ +
+

警告: この方法は避けてください。これはマークアップを増加させ、可読性を下げます。コンテンツと振る舞いが正しく分離されておらず、バグの発見が困難になります。

+
+ +

DOM 要素のプロパティ

+ +
// myButton は button 要素と仮定します
+myButton.onclick = function(event){alert('Hello world')}
+
+ +

この関数は 1 つの event 引数を取るように定義できます。返り値は HTML の仕様で定義された特別な方法で処理されます

+ +

この書き方の問題は、各要素の各イベント毎に 1 つだけしかハンドラーを設定できないことです。

+ +

Event インターフェイスへのアクセス

+ +

イベントハンドラーは (DOM 要素や文書、 {{domxref("window")}} オブジェクト等を含めた) 様々なオブジェクトに追加されるでしょう。イベントが発生すると、イベントオブジェクトが生成され順番にイベントリスナーが呼ばれます。

+ +

{{domxref("Event")}} インターフェイスは、イベントハンドラーの内部からアクセス可能で、第 1 引数としてイベントオブジェクトを介して渡されます。以下のシンプルな例は、イベントハンドラーにどのようにイベントオブジェクトが渡され、その中でどのように使われるかを示します。

+ +
function print(evt) {
+  // evt 引数は自動的にイベントオブジェクトに割り当てられます
+  // console.log と alert の違いに注意してください
+  console.log('print:', evt)
+  alert(evt)
+}
+// どの関数も意味を持つ適切な名前を付けてください
+table_el.onclick = print
+
+ + + + diff --git a/files/ja/orphaned/web/guide/events/event_handlers/index.html b/files/ja/orphaned/web/guide/events/event_handlers/index.html new file mode 100644 index 0000000000..7cdd63d81e --- /dev/null +++ b/files/ja/orphaned/web/guide/events/event_handlers/index.html @@ -0,0 +1,173 @@ +--- +title: DOM onevent ハンドラー +slug: orphaned/Web/Guide/Events/Event_handlers +tags: + - Beginner + - DOM + - DOM Beginner + - NeedsBeginnerUpdate + - NeedsUpdate +translation_of: Web/Guide/Events/Event_handlers +original_slug: Web/Guide/Events/Event_handlers +--- +

ウェブプラットフォームでは、DOM イベントの通知を受け取るための方法をいくつか提供しています。よく使われる方法は2つあり、 {{domxref("EventTarget.addEventListener", "addEventListener()")}} と、特定の onevent ハンドラーです。このページでは、後者がどのように機能するのかについて注目します。

+ +

onevent ハンドラーの登録

+ +

onevent ハンドラーは特定の DOM 要素のプロパティで、その要素がイベントに対してどのように反応するかを管理します。要素には、対話的なもの (リンク、ボタン、画像、フォームなど) と対話的ではないもの (基本の <body> 要素など) があります。イベントとは、以下のようなアクションのことです。

+ +
    +
  • クリックされた
  • +
  • キーの押下が検出された
  • +
  • フォーカスを受け取った
  • +
+ +

onevent ハンドラーは通常、onclick, onkeypress, onfocus など、反応するイベントに従って名前が付けられています。

+ +

on<…> イベントハンドラーを指定することで、指定されたオブジェクトの特定のイベント ({{event("click")}} など) に対してさまざまな方法で指定することができます。

+ +
    +
  • 要素に on<eventtype> という名前の HTML {{Glossary("attribute", "属性")}}を追加する方法。
    + <button onclick="handleClick()">,
  • +
  • または、JavaScript から対応する {{Glossary("property/JavaScript", "property")}} を設定する方法。
    + document.querySelector("button").onclick = function(event) { … }.
  • +
+ +

onevent イベントハンドラープロパティは、1 つのイベントハンドラーを割り当てることができる一種のプレースホルダーとして機能します。与えられたオブジェクト上の同じイベントに対して複数のハンドラーをインストールできるようにするには、その addEventListener() メソッドを呼び出して、オブジェクト上の与えられたイベントに対するハンドラーのリストを管理することができます。ハンドラーは、その {{domxref("EventTarget.removeEventListener", "removeEventListener()")}} 関数を呼び出すことで、オブジェクトから削除することができます。

+ +

要素に適用されるイベントが発生すると、そのイベントハンドラーが次々と呼び出され、イベントを処理できるようになります。自分で呼び出す必要はありませんが、多くの場合、イベントの発生を簡単にシミュレートするために呼び出すことができます。例えば、ボタンオブジェクト myButton を指定した場合、 myButton.onclick(myEventObject) を実行することでイベントハンドラーを直接呼び出すことができます。イベントハンドラーがイベントオブジェクトからデータにアクセスしない場合は、 onclick() を呼び出すときにイベントを省略することができます。

+ +

これは、イベントハンドラーのいずれかがイベントオブジェクト自身に対して {{domxref("Event.stopPropagation", "stopPropagation()")}} を呼び出すことでイベントの処理を明示的に停止しない限り、すべてのハンドラーが呼び出されるまで続きます。

+ +

要素以外のオブジェクト

+ +

イベントハンドラーはまた、 {{ domxref("window") }}, {{ domxref("document") }}, {{ domxref("XMLHttpRequest") }} などを含む、イベントを生成する多くの要素以外のオブジェクトのプロパティを使用して設定することもできます。例えば、 progress イベントが XMLHttpRequest のインスタンスで発生した場合は次のようになります。

+ +
const xhr = new XMLHttpRequest();
+xhr.onprogress = function() { … };
+ +

HTML の onevent 属性

+ +

HTML 要素には onevent という名前の属性があり、これを利用して HTML コード内に直接イベントのハンドラーを登録することができます。要素が HTML から構築されると、その onevent 属性の値がその要素を表す DOM オブジェクトにコピーされるので、JavaScript を使って属性の値にアクセスすると、HTML で設定された値が得られます。

+ + + +

HTML の属性値への更なる変更は {{domxref("Element/setAttribute", "setAttribute")}} メソッドで行うことができます。 JavaScript プロパティを変更しても効果あありません。

+ +

HTML

+ +

このような HTML 文書があったとします。

+ +
<p>Demonstrating quirks of <code>on<em>event</em></code> HTML attributes on
+   <a onclick="log('Click!')">these three words</a>.
+</p>
+
+<div></div>
+ +

JavaScript

+ +

この JavaScript は、 HTML 属性の値が JavaScript オブジェクトのプロパティの変更によって影響を受けないことを示しています。

+ +
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>`);
+ +

結果

+ +

{{ EmbedLiveSample('HTML_onevent_attributes', '', '', '', 'Web/Guide/Events/Event_handlers') }}

+ +

歴史的な理由から、{{HTMLElement("body")}} および {{HTMLElement("frameset")}} 要素の一部の属性/プロパティは、実際にはその親 {{domxref("Window")}} オブジェクトにイベントハンドラーを設定します。(HTML 仕様はこれらを {{domxref("GlobalEventHandlers/onblur", "onblur")}}, {{domxref("GlobalEventHandlers/onerror", "onerror")}}, {{domxref("GlobalEventHandlers/onfocus", "onfocus")}}, {{domxref("GlobalEventHandlers/onload", "onload")}}, {{domxref("GlobalEventHandlers/onscroll", "onscroll")}} と命名しています。)

+ +

イベントハンドラーの引数、this の結びつけ、および返値

+ +

イベントハンドラーが HTML 属性として指定されている場合、指定されたコードは次の引数を持つ関数にラップされます。

+ +
    +
  • event - {domxref("GlobalEventHandlers.onerror", "onerror")}} を除くすべてのイベントハンドラー。
  • +
  • event, source, lineno, colno, error - {{domxref("GlobalEventHandlers.onerror", "onerror")}} のイベントハンドラー。なお、 event 引数には、実際にはエラーメッセージが文字列として含まれています。
  • +
+ +

イベントハンドラーが呼び出されると、ハンドラー内の this キーワードは、ハンドラーが登録されている DOM 要素に設定されます。詳しくは、this キーワードのドキュメントを参照してください。

+ +

ハンドラーからの返値は、イベントが取り消されるかどうかを決定します。返値値の具体的な処理はイベントの種類によって異なります。詳細については、HTML 仕様の「イベントハンドラー処理アルゴリズム」を参照してください。

+ +

イベントハンドラーが呼び出されたとき

+ +
+

作成中 (非捕獲リスナー)

+
+ +

用語集

+ +

イベントハンドラーという用語は、次のように使用されます。

+ +
    +
  • イベントの通知を受けるように登録されている関数またはオブジェクト
  • +
  • または、より具体的には、<button onclick="alert(this)">window.onload = function() { … }など、HTML の on… 属性または Web API のプロパティを介してイベントリスナーを登録するメカニズム。
  • +
+ +

イベントを待ち受けするためのさまざまな方法を議論するときは、

+ +
    +
  • イベントリスナーは、{{domxref("EventTarget.addEventListener()")}} によって登録された関数またはオブジェクトを参照します。
  • +
  • 一方、イベントハンドラーon... 属性またはプロパティを介して登録された関数を指します。
  • +
+ +

仕様書

+ + + + + + + + + + + + + + + + + + + + + +
仕様書状態備考
{{SpecName('HTML WHATWG', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML5 W3C')}}
+ +

ブラウザーの互換性

+ +

イベントハンドラープロパティが存在することの検出

+ +

JavaScript の {{jsxref("Operators/in", "in")}} 演算子でイベントハンドラープロパティの存在を検出することができます。例えば、以下のようになります。

+ +
if ("onsomenewfeature" in window) {
+  /* do something amazing */
+}
+
+ +

イベントハンドラーとプロトタイプ

+ +

DOM プロトタイプオブジェクトには、IDL で定義された属性の値を設定したり、アクセスしたりすることはできません。つまり、例えば Window.prototype.onload を変更することはできません。以前は、 Gecko では イベントハンドラー (onload など) が IDL 属性として実装されていなかったので可能だったのですが、現在はできなくなりました。これにより互換性が向上します。

diff --git a/files/ja/orphaned/web/guide/events/index.html b/files/ja/orphaned/web/guide/events/index.html new file mode 100644 index 0000000000..35f1c1184b --- /dev/null +++ b/files/ja/orphaned/web/guide/events/index.html @@ -0,0 +1,51 @@ +--- +title: イベント開発者ガイド +slug: orphaned/Web/Guide/Events +tags: + - DOM + - Event + - Guide + - events +translation_of: Web/Guide/Events +original_slug: Web/Guide/Events +--- +
{{draft()}}
+ +

イベントは、ウェブページの生存期間に起こる様々な出来事を非同期に扱うために使用されるデザインパターンと、さまざまな種類の多数の出来事についての名前、特性付け、利用の両方を指します。

+ +

概要ページでは、デザインパターンの紹介と最近のウェブブラウザーで定義され行われる出来事の種類の概要を提供します。

+ +

カスタムイベントページでは、独自コードでイベントコードのデザインパターンを使用して、ユーザーオブジェクトによって発行される新しいイベント型を定義し、それらのイベントを処理するためのリスナー関数を登録し、ユーザーのコードでイベントを発生させる方法について説明します。

+ +

その他のページでは、ウェブブラウザーで定義されているさまざまな種類のイベントの使用方法について説明します。残念なことに、これらのイベントはウェブブラウザーの進化に合わせて部分的に定義されてきたため、最新のウェブブラウザーに組み込まれている、または定義されているイベントの満足のいく体系的な特徴付けはありません。

+ +

ウェブブラウザーが実行されている端末は、例えば実世界での場所や方向の変化によってイベントが発生することがあり、これは方向座標系上のページおよび三次元変換の使用上のページで部分的に説明されているとおりです。これは端末の縦の方向が変化した場合とは異なりますが、似ています。

+ +

ブラウザーが表示されるウィンドウがイベントを発生させることがあります。例えば、ユーザーがウィンドウを最大化したり、その他の変更があったりすると、サイズ変更イベントが発生します。

+ +

ウェブページを読み込んでいるプロセスがユーザーに表示するためにウェブページをダウンロードし、解析し、レンダリングする様々な段階を補完するための応答としてイベントを発生することがあります。

+ +

ウェブページのコンテンツへのユーザーの操作がイベントを発生させることがあります。ユーザーの操作によって発生したイベントは、ブラウザー設計の初期の頃に進化し、イベントが呼び出される順序およびその順序を制御することができる方法を定義する複雑なシステムを含んでいます。さまざまな種類のユーザー対話型イベントには、以下のものがあります。

+ + + +

構造面やコンテンツにおけるウェブページの変更が、いくつかのイベントを発生させることがあり、変化イベントのページで説明されているとおりですが、これらのイベントはより軽い Mutation Observer のアプローチに置き換えられて非推奨になっています。

+ +

HTML 文書に埋め込まれたメディアストリームがいくつかのイベントを発生させることがあり、メディアイベントページで説明されている通りです。

+ +

ウェブページによって行われるネットワークリクエストが、いくつかのイベントを発生させることがあります。

+ +

他にも、ウェブブラウザーが定義したイベントの発生源で、このガイドではまだ言及していないものがたくさんあります。

+ +
+

メモ: このイベント開発者ガイドは継続的な作業が必要です。構造を再編したりページを書き直したりする必要があります。イベントについて知っておくことが必要なすべてをここで提供できるようになりたいと考えています。

+
+ +

文書

+ +

{{LandingPageListSubpages}}

diff --git a/files/ja/orphaned/web/guide/events/orientation_and_motion_data_explained/index.html b/files/ja/orphaned/web/guide/events/orientation_and_motion_data_explained/index.html new file mode 100644 index 0000000000..637b1cc413 --- /dev/null +++ b/files/ja/orphaned/web/guide/events/orientation_and_motion_data_explained/index.html @@ -0,0 +1,50 @@ +--- +title: 方向および動きとして示されるデータ +slug: orphaned/Web/Guide/Events/Orientation_and_motion_data_explained +tags: + - DOM + - Mobile + - Motion + - NeedsContent + - Orientation + - Responsive Design + - páginas_a_traducir + - rotation +translation_of: Web/Guide/Events/Orientation_and_motion_data_explained +original_slug: Web/Guide/Events/Orientation_and_motion_data_explained +--- +

{{ Draft() }}

+

方向や動きのイベントを使用するときは、ブラウザから与えられる値の意味を理解することが重要です。この記事では操作時の座標システムに関する詳細情報と、それらの使い方を説明します。

+

座標フレームについて

+

{{原語併記("座標フレーム", "coordinate frame")}} は、オブジェクトに関する 3 軸 (X、Y、Z) の方向が定義されているシステムです。方向や動きのイベントを使用するときに考慮する座標フレームは 2 つあります:

+

地球座標フレーム

+

{{原語併記("地球座標フレーム", "Earth coordinate frame")}} は、地球の中心に固定されている座標フレームです。すなわち、軸は重力によって引かれる力および標準的な磁北方向に基づいて揃えられます。私たちは大文字 ("X"、"Y"、"Z") を、地球座標フレームの軸を示すために使用します。

+
    +
  • X 軸は地面に沿ってたどり、Y 軸と直交します。また、軸の正の方向が東を指します (従って、負の方向は西を指します)。
  • +
  • Y 軸は地面に沿ってたどり、正の方向が真北 (すなわち北極であり、磁北ではありません) を、負の方向が真南を指します。
  • +
  • Z 軸は地面に直交します。これは、デバイスと地球の中心との間に引かれた線と考えてください。Z 座標の値は正の方向が上向き (地球の中心から遠ざかる)、負の方向が下向き (地球の中心に向かう) です。
  • +
+

デバイス座標フレーム

+

{{原語併記("デバイス座標フレーム", "Device coordinate frame")}} は、デバイスの中心に固定された座標フレームです。私たちは小文字 ("x"、"y"、"z") を、デバイス座標フレームの軸を示すために使用します。

+

axes.png

+
    +
  • x 軸はスクリーンの水平面にあり、正の方向が右を、負の方向が左を指します。
  • +
  • y 軸はスクリーンの水平面にあり、正の方向が上端側を、負の方向が下端側を指します。
  • +
  • z 軸はスクリーンやキーボードに直交しており、正の方向がスクリーンから外側へ伸びていきます。
  • +
+
+ 注意: 電話機やタブレットでは、デバイスの方向が常にスクリーンの標準的な方向に対して考えられます。これは、ほとんどのデバイスで "ポートレート" 方向になります。ラップトップコンピュータでは、方向はキーボードに対して考えられます。補正するためにデバイスの方向の変化を検知したい場合は、orientationchange イベントを使用できます。
+

回転について

+

回転は、デバイス座標フレームと地球座標フレームとの度合いの違いという点から各軸で表現され、またそれは度単位で測られます

+

Alpha

+

z 軸を中心にした回転、すなわちデバイスをひねるようにすると、alpha 回転角が変化します:

+

alpha.png

+

alpha 角はデバイスの上端が地球の北極をまっすぐ向いているときが 0 度であり、デバイスが左へ回転するのに従って増加します。

+

Beta

+

x 軸を中心にした回転、すなわちデバイスを向こう側やユーザ側へ向かって傾けると、beta 回転角が変化します:

+

beta.png

+

beta 角はデバイスの上端および下端から地球の表面までの距離がどちらも同じであるときが 0 度であり、デバイスを前方へ傾けるのに従って 180 度まで増加、後方へ傾けるのに従って -180 度まで減少します。

+

Gamma

+

y 軸を中心にした回転、すなわちデバイスを左右に傾けると、gamma 回転角が変化します:

+

gamma.png

+

gamma 角はデバイスの左端および右端から地球の表面までの距離がどちらも同じであるときが 0 度であり、デバイスを右へ傾けるのに従って 90 度まで増加、左へ傾けるのに従って -90 度まで減少します。

diff --git a/files/ja/orphaned/web/guide/events/overview_of_events_and_handlers/index.html b/files/ja/orphaned/web/guide/events/overview_of_events_and_handlers/index.html new file mode 100644 index 0000000000..4e30c38418 --- /dev/null +++ b/files/ja/orphaned/web/guide/events/overview_of_events_and_handlers/index.html @@ -0,0 +1,137 @@ +--- +title: Overview of Events and 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 +--- +
+

This overview of events and event handling explains the code design pattern used to react to incidents occurring when a browser accesses a web page, and it summarizes the types of such incidents modern web browsers can handle.

+
+ +

Events and event handling provide a core technique in JavaScript for reacting to incidents occurring when a browser accesses a web page, including events from preparing a web page for display, from interacting with the content of the web page,  relating to the device on which the browser is running, and from many other causes such as media stream playback or animation timing.

+ +

Events and event handling become central to web programming with the addition of the language to browsers, accompanying a switch in the rendering architecture of browsers from fetch and load page rendering to event driven, reflow based, page rendering. Initially, browsers wait, until they receive all of the resources associated with a page, to parse, process, draw, and present the page to the user. The displayed page remains unchanged until the browser requests a new page. 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 e.g., downloads an image that can now be drawn on the screen, the completion of parsing a resource by the browser e.g., processes the HTML content of a page, the interaction of a user with the contents of the page e.g., clicks a button. Douglas Crockford explains this change effectively in several lectures, notably his talk, An Inconvenient API: The Theory of the DOM, which shows the change in flow from the original browser flow

+ +
A comparison of the sequential and event-driven browser load sequences.
+ +

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 this one.) Currently, all execution environments for JavaScript code use events and event handling.

+ +

The event design pattern

+ +

The event system, at its core, is simply a programming design pattern. The pattern starts with an agreement over a kind of event and:

+ +
    +
  • the name String used for the event,
  • +
  • the type of the data structure used to represent the key properties of that event, and
  • +
  • the JavaScript object which will 'emit' that event.
  • +
+ +

The pattern is implemented by

+ +
    +
  • defining a JavaScript function which takes as an argument the data structure which was agreed upon, and
  • +
  • registering the function using the name String with the object which will emit the event.
  • +
+ +

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 article on custom events. The pattern is also used by modern web browsers which define many events emitted in response to user input or browser activity.

+ +

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 EventPrototype object. Browsers use as the registration method for the function which will handle those data structures a method called addEventListener 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.

+ +

Button Event Handler Demo

+ +

For example, browser button elements are intended to emit events named 'click' 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 button as:

+ +
<button id="buttonOne">Click here to emit a 'click' event</button>
+ +

and, in our JavaScript code, we could first define a function to listen to that 'click' event:

+ +
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 );
+};
+ +

and second register our function with the the Button object, either on the scripting side using the DOM (Document Object Model) representation of the HTML page:

+ +
var buttonDOMElement = document.querySelector('#buttonOne');
+buttonDOMElement.addEventListener('click', example_click_handler);
+ +

or within the HTML page by adding the function as the value of the 'onclick' attribute, although this second approach is usually only used in very simple web pages.

+ +

{{ EmbedLiveSample('Button_Event_Handler') }}

+ +

This code relies on the agreement that there is a kind of event called 'click' which will call any listener (or 'handler') function with an Event object argument (actually, in this case a derivative MouseEvent object) and which will be fired by HTML button 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 buttonDOMElement JavaScript object would call the example_click_handler function with an Event 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 ev object since it is passed as an argument; the object has information about the event, notably the time at which the event occurred.

+ +

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:

+ +
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);
+
+ +

so that this code will only be executed after the document object emits the 'DOMContentLoaded' 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.

+ +

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.

+ +

Notable events

+ +

Web browsers define a large number of events so it is not practical to list them all. The Event Reference attempts to maintain a list of the standard Events used in modern web browsers.

+ +

In general, we can distinguish events of different kinds based on the object emitting the event including:

+ +
    +
  • the window object, such as due to resizing the browser,
  • +
  • the window.screen object, such as due to changes in device orientation,
  • +
  • the document object, including the loading, modification, user interaction, and unloading of the page,
  • +
  • the objects in the DOM (document object model) tree including user interactions or modifications,
  • +
  • the XMLHttpRequest objects used for network requests, and
  • +
  • the media objects such as audio and video, when the media stream players change state.
  • +
+ +

although this list is currently incomplete.

+ +

Some notable events are:

+ +
+

Note: 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 this web page or in this Stack Overflow question.

+
+ +
    +
  • the global object window emits an event called 'load' 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,
  • +
  • the global object window emits an event called 'resize' when the height or the width of the browser window is changed by a user,
  • +
  • the DOM object document representing the HTML document emits an event called 'DOMContentLoaded' when the document has finished loading,
  • +
  • the DOM node objects such as div or button emit an event called 'click' when the user presses the mouse button while the mouse pointer is on top of the DOM node in the HTML page.
  • +
+ +

 

+ +

The Event object hierarchy

+ +

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 EventPrototype object.

+ +

A partial diagram of the class hierarchy of event objects is:

+ +
+

Note: This diagram is incomplete.

+
+ +

+ +

The Web API Documentation contains a page defining the Event object which also includes the known DOM event subclasses of the Event object.

+ +

Documents

+ +

Three sources on the MDN (Mozilla Developer Network) web site are particularly useful for programmers wanting to work with events:

+ + + +

 

+ +

 

+ +

 

diff --git a/files/ja/web/api/detecting_device_orientation/index.html b/files/ja/web/api/detecting_device_orientation/index.html deleted file mode 100644 index 8dc09fea8b..0000000000 --- a/files/ja/web/api/detecting_device_orientation/index.html +++ /dev/null @@ -1,228 +0,0 @@ ---- -title: デバイスの方向の検出 -slug: Web/API/Detecting_device_orientation -tags: - - API - - Device Orientation - - Firefox OS - - Intermediate - - Mobile - - Motion - - Orientation - - Reference - - WebAPI -translation_of: Web/API/Detecting_device_orientation ---- -
{{SeeCompatTable}}
- -

Web を利用可能なデバイスは、自身の方向を特定できるようになってきました。つまりデバイスは、重力との関係による自身の向きの変化を示すデータを報告できます。特に携帯電話のようなハンドヘルドデバイスは、表示内容が直立し続けるよう自動的に回転させるためにこの情報を使用でき、画面の幅が高さより大きくなるようにデバイスを回転させたときは、Web コンテンツをワイドスクリーン表示にします。

- -

方向の情報を制御する JavaScript イベントが 2 つあります。ひとつは {{domxref("DeviceOrientationEvent")}} であり、加速度センサーがデバイスの方向の変化を検出したときに発生します。Orientation イベントが報告するデータを受け取って処理することで、ユーザがデバイスを動かすことによる方向や高さの変化に対してインタラクティブに応答できるようになります。

- -

もうひとつのイベントは {{domxref("DeviceMotionEvent")}} であり、加速度が変化したときに発生します。こちらは方向ではなく加速度の変化を監視することが、{{domxref("DeviceOrientationEvent")}} との違いです。一般的に {{domxref("DeviceMotionEvent")}} を検出できるセンサーには、可動部があるストレージ装置を保護するためラップトップパソコンに内蔵するものも含みます。{{domxref("DeviceOrientationEvent")}} は、モバイルデバイスでとても一般的です。

- -

orientation イベントを処理する

- -

方向の変化を受け取り始めるには、{{event("deviceorientation")}} イベントをリッスンします:

- -
-

注記: gyronorm.js は、モバイルデバイスの加速度センサーやジャイロスコープのデータを正規化するためのポリフィルです。これは、デバイスの方向のサポート状況の違いを克服するのに役立ちます。

-
- -
window.addEventListener("deviceorientation", handleOrientation, true);
-
- -

イベントリスナ (この例では handleOrientation() という名前の JavaScript 関数) を登録すると、リスナ関数は最新の方向データとともに、周期的に呼び出されます。

- -

Orientation イベントは 4 つの値を持ちます:

- -
    -
  • {{domxref("DeviceOrientationEvent.absolute")}}
  • -
  • {{domxref("DeviceOrientationEvent.alpha")}}
  • -
  • {{domxref("DeviceOrientationEvent.beta")}}
  • -
  • {{domxref("DeviceOrientationEvent.gamma")}}
  • -
- -

イベントハンドラ関数は以下のようなものです:

- -
function handleOrientation(event) {
-  var absolute = event.absolute;
-  var alpha    = event.alpha;
-  var beta     = event.beta;
-  var gamma    = event.gamma;
-
-  // 新たな方向データに基づいて処理を行う
-}
-
- -

方向として示される値

- -

それぞれの軸で報告される値は、標準座標系の軸を中心にした回転量を表します。これらは方向および動きとして示されるデータの記事で詳しく説明しており、ここでは概要を記載します。

- -
    -
  • {{domxref("DeviceOrientationEvent.alpha")}} の値は z 軸を中心にしたデバイスの動きを表し、0 から 360 の範囲による度数で表されます。
  • -
  • {{domxref("DeviceOrientationEvent.beta")}} の値は x 軸を中心にしたデバイスの動きを表し、-180 から 180 の範囲の値による度数で表されます。これはデバイスの前後の動きです。
  • -
  • {{domxref("DeviceOrientationEvent.gamma")}} の値は y 軸を中心にしたデバイスの動きを表し、-90 から 90 の範囲の値による度数で表されます。これはデバイスの左右の動きです。
  • -
- -

- -

このサンプルは方向を検出可能なデバイス上で、{{event("deviceorientation")}} イベントをサポートするブラウザを実行する場合に動作します。

- -

庭にボールがあると考えます:

- -
<div class="garden">
-  <div class="ball"></div>
-</div>
-
-<pre class="output"></pre>
-
- -

庭の幅は 200 ピクセルであり (小さな庭です)、ボールは中心にあります:

- -
.garden {
-  position: relative;
-  width : 200px;
-  height: 200px;
-  border: 5px solid #CCC;
-  border-radius: 10px;
-}
-
-.ball {
-  position: absolute;
-  top   : 90px;
-  left  : 90px;
-  width : 20px;
-  height: 20px;
-  background: green;
-  border-radius: 100%;
-}
-
- -

デバイスを動かすと、その動きに応じてボールが移動します:

- -
var ball   = document.querySelector('.ball');
-var garden = document.querySelector('.garden');
-var output = document.querySelector('.output');
-
-var maxX = garden.clientWidth  - ball.clientWidth;
-var maxY = garden.clientHeight - ball.clientHeight;
-
-function handleOrientation(event) {
-  var x = event.beta;  // -180 から 180 の範囲で角度を示す
-  var y = event.gamma; // -90 から 90 の範囲で角度を示す
-
-  output.innerHTML  = "beta : " + x + "\n";
-  output.innerHTML += "gamma: " + y + "\n";
-
-  // デバイスをひっくり返したくはないため、
-  // x の値を -90 から 90 の範囲に制限する
-  if (x >  90) { x =  90};
-  if (x < -90) { x = -90};
-
-  // 計算を容易にするため、x および y の値の範囲を
-  // 0 から 180 に変換する
-  x += 90;
-  y += 90;
-
-  // 10 は、ボールのサイズの半分である。
-  // これにより、配置場所をボールの中心に合わせる
-  ball.style.top  = (maxX*x/180 - 10) + "px";
-  ball.style.left = (maxY*y/180 - 10) + "px";
-}
-
-window.addEventListener('deviceorientation', handleOrientation);
-
- -

結果を以下に示します:

- -
{{EmbedLiveSample('Orientation_example', '230', '260')}}
- -
-

警告: Chrome と Firefox では角度の扱い方が異なり、一部の軸の向きが逆になっています。

-
- -

motion イベントを処理する

- -

motion イベントは orientation イベントと同じ方法で扱えますが、イベント名は {{event("devicemotion")}} になります。

- -
window.addEventListener("devicemotion", handleMotion, true);
- -

実際どのように変化したかの情報は、HandleMotion 関数のパラメータとして渡す {{domxref("DeviceMotionEvent")}} オブジェクトが提供します。

- -

motion イベントは 4 つのプロパティを持ちます:

- -
    -
  • {{domxref("DeviceMotionEvent.acceleration")}}
  • -
  • {{domxref("DeviceMotionEvent.accelerationIncludingGravity")}}
  • -
  • {{domxref("DeviceMotionEvent.rotationRate")}}
  • -
  • {{domxref("DeviceMotionEvent.interval")}}
  • -
- -

動きとして示される値

- -

{{domxref("DeviceMotionEvent")}} オブジェクトは Web 開発者に、デバイスの位置や方向が変化した速度の情報を提供します。変化量は 3 つの軸 (詳しくは方向および動きとして示されるデータをご覧ください) に沿って表します。

- -

{{domxref("DeviceMotionEvent.acceleration","acceleration")}} および {{domxref("DeviceMotionEvent.accelerationIncludingGravity","accelerationIncludingGravity")}} で対応する軸は以下のとおりです:

- -
    -
  • x: 西から東へ向かう軸を表します。
  • -
  • y: 南から北へ向かう軸を表します。
  • -
  • z: 地面から直立する軸を表します。
  • -
- -

{{domxref("DeviceMotionEvent.rotationRate","rotationRate")}} では状況が若干異なります。こちらの情報はそれぞれ以下のように対応します:

- -
    -
  • alpha: スクリーン (デスクトップ環境ではキーボード) から直立する軸を表します。
  • -
  • beta: スクリーンの面 (デスクトップ環境ではキーボード) の左から右へ向かう軸に沿った回転量を表します。
  • -
  • gamma: スクリーンの面 (デスクトップ環境ではキーボード) の下から上へ向かう軸に沿った回転量を表します。
  • -
- -

最後に {{domxref("DeviceMotionEvent.interval","interval")}} は、デバイスからデータを取得する間隔をミリ秒単位で表します。

- -

仕様

- - - - - - - - - - - - - - - - -
仕様書策定状況コメント
{{SpecName('Device Orientation')}}{{Spec2('Device Orientation')}}最初の仕様
- -

ブラウザ実装状況

- -
-

DeviceMotionEvent

- - - -

{{Compat("api.DeviceMotionEvent")}}

- -

DeviceOrientationEvent

- - - -

{{Compat("api.DeviceOrientationEvent")}}

-
- -

関連情報

- - diff --git a/files/ja/web/api/document_object_model/events/index.html b/files/ja/web/api/document_object_model/events/index.html deleted file mode 100644 index 1d8b1974a6..0000000000 --- a/files/ja/web/api/document_object_model/events/index.html +++ /dev/null @@ -1,88 +0,0 @@ ---- -title: イベントと DOM -slug: Web/API/Document_Object_Model/Events -tags: - - DOM - - Guide - - ガイド -translation_of: Web/API/Document_Object_Model/Events ---- -
{{DefaultAPISidebar("DOM")}}
- -

はじめに

- -

この章では DOM のイベントモデルを説明します。この Event インターフェイス自身は、 DOM のノード上にイベントを登録する為のインターフェイスと同様であり、イベントリスナーであるとも言えます。いくつかの長い例は、様々な Event インターフェイスがどのように他と関連するかを示します。

- -

DOM レベル 3 イベントの原案に、DOM を通して 3 つのフェーズから構成されるイベントフローを明確に説明した素晴らしい説明図があります。

- -

また、イベントが DOM 内をどのように伝播するかについては更に詳細なコード例、例 5: イベント伝播 (propagation) を参照してください。

- -

イベントリスナーの登録

- -

DOM の要素にイベントハンドラーを登録する方法は 3 つあります。

- -

{{domxref("EventTarget.addEventListener")}}

- -
// myButton は button 要素だと仮定します
-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')
-}
-
- -

これが最近のウェブページで使われる方法です。

- -
-

注: Internet Explorer 6 から 8 はこの方法をサポートせず、 {{domxref("EventTarget.attachEvent")}} という似た API を代わりにサポートします。ブラウザー間の互換性を確保するには、数多くある JavaScript ライブラリのうちの一つを使用してください。

-
- -

さらに詳細を知りたい場合は {{domxref("EventTarget.addEventListener")}} のリファレンスを参照してください。

- -

HTML 属性

- -
<button onclick="alert('Hello world!')">
-
- -

HTML 属性に書かれたこの JavaScript コードには、 event 引数を通してイベントオブジェクトが渡されます。返値は HTML の仕様で定義された特別な方法で処理されます

- -
-

警告: この方法は避けてください。これはマークアップを増加させ、可読性を下げます。コンテンツと振る舞いが正しく分離されておらず、バグの発見が困難になります。

-
- -

DOM 要素のプロパティ

- -
// myButton は button 要素と仮定します
-myButton.onclick = function(event){alert('Hello world')}
-
- -

この関数は 1 つの event 引数を取るように定義できます。返り値は HTML の仕様で定義された特別な方法で処理されます

- -

この書き方の問題は、各要素の各イベント毎に 1 つだけしかハンドラーを設定できないことです。

- -

Event インターフェイスへのアクセス

- -

イベントハンドラーは (DOM 要素や文書、 {{domxref("window")}} オブジェクト等を含めた) 様々なオブジェクトに追加されるでしょう。イベントが発生すると、イベントオブジェクトが生成され順番にイベントリスナーが呼ばれます。

- -

{{domxref("Event")}} インターフェイスは、イベントハンドラーの内部からアクセス可能で、第 1 引数としてイベントオブジェクトを介して渡されます。以下のシンプルな例は、イベントハンドラーにどのようにイベントオブジェクトが渡され、その中でどのように使われるかを示します。

- -
function print(evt) {
-  // evt 引数は自動的にイベントオブジェクトに割り当てられます
-  // console.log と alert の違いに注意してください
-  console.log('print:', evt)
-  alert(evt)
-}
-// どの関数も意味を持つ適切な名前を付けてください
-table_el.onclick = print
-
- - - - diff --git a/files/ja/web/guide/events/event_handlers/index.html b/files/ja/web/guide/events/event_handlers/index.html deleted file mode 100644 index 5123afd667..0000000000 --- a/files/ja/web/guide/events/event_handlers/index.html +++ /dev/null @@ -1,172 +0,0 @@ ---- -title: DOM onevent ハンドラー -slug: Web/Guide/Events/Event_handlers -tags: - - Beginner - - DOM - - DOM Beginner - - NeedsBeginnerUpdate - - NeedsUpdate -translation_of: Web/Guide/Events/Event_handlers ---- -

ウェブプラットフォームでは、DOM イベントの通知を受け取るための方法をいくつか提供しています。よく使われる方法は2つあり、 {{domxref("EventTarget.addEventListener", "addEventListener()")}} と、特定の onevent ハンドラーです。このページでは、後者がどのように機能するのかについて注目します。

- -

onevent ハンドラーの登録

- -

onevent ハンドラーは特定の DOM 要素のプロパティで、その要素がイベントに対してどのように反応するかを管理します。要素には、対話的なもの (リンク、ボタン、画像、フォームなど) と対話的ではないもの (基本の <body> 要素など) があります。イベントとは、以下のようなアクションのことです。

- -
    -
  • クリックされた
  • -
  • キーの押下が検出された
  • -
  • フォーカスを受け取った
  • -
- -

onevent ハンドラーは通常、onclick, onkeypress, onfocus など、反応するイベントに従って名前が付けられています。

- -

on<…> イベントハンドラーを指定することで、指定されたオブジェクトの特定のイベント ({{event("click")}} など) に対してさまざまな方法で指定することができます。

- -
    -
  • 要素に on<eventtype> という名前の HTML {{Glossary("attribute", "属性")}}を追加する方法。
    - <button onclick="handleClick()">,
  • -
  • または、JavaScript から対応する {{Glossary("property/JavaScript", "property")}} を設定する方法。
    - document.querySelector("button").onclick = function(event) { … }.
  • -
- -

onevent イベントハンドラープロパティは、1 つのイベントハンドラーを割り当てることができる一種のプレースホルダーとして機能します。与えられたオブジェクト上の同じイベントに対して複数のハンドラーをインストールできるようにするには、その addEventListener() メソッドを呼び出して、オブジェクト上の与えられたイベントに対するハンドラーのリストを管理することができます。ハンドラーは、その {{domxref("EventTarget.removeEventListener", "removeEventListener()")}} 関数を呼び出すことで、オブジェクトから削除することができます。

- -

要素に適用されるイベントが発生すると、そのイベントハンドラーが次々と呼び出され、イベントを処理できるようになります。自分で呼び出す必要はありませんが、多くの場合、イベントの発生を簡単にシミュレートするために呼び出すことができます。例えば、ボタンオブジェクト myButton を指定した場合、 myButton.onclick(myEventObject) を実行することでイベントハンドラーを直接呼び出すことができます。イベントハンドラーがイベントオブジェクトからデータにアクセスしない場合は、 onclick() を呼び出すときにイベントを省略することができます。

- -

これは、イベントハンドラーのいずれかがイベントオブジェクト自身に対して {{domxref("Event.stopPropagation", "stopPropagation()")}} を呼び出すことでイベントの処理を明示的に停止しない限り、すべてのハンドラーが呼び出されるまで続きます。

- -

要素以外のオブジェクト

- -

イベントハンドラーはまた、 {{ domxref("window") }}, {{ domxref("document") }}, {{ domxref("XMLHttpRequest") }} などを含む、イベントを生成する多くの要素以外のオブジェクトのプロパティを使用して設定することもできます。例えば、 progress イベントが XMLHttpRequest のインスタンスで発生した場合は次のようになります。

- -
const xhr = new XMLHttpRequest();
-xhr.onprogress = function() { … };
- -

HTML の onevent 属性

- -

HTML 要素には onevent という名前の属性があり、これを利用して HTML コード内に直接イベントのハンドラーを登録することができます。要素が HTML から構築されると、その onevent 属性の値がその要素を表す DOM オブジェクトにコピーされるので、JavaScript を使って属性の値にアクセスすると、HTML で設定された値が得られます。

- - - -

HTML の属性値への更なる変更は {{domxref("Element/setAttribute", "setAttribute")}} メソッドで行うことができます。 JavaScript プロパティを変更しても効果あありません。

- -

HTML

- -

このような HTML 文書があったとします。

- -
<p>Demonstrating quirks of <code>on<em>event</em></code> HTML attributes on
-   <a onclick="log('Click!')">these three words</a>.
-</p>
-
-<div></div>
- -

JavaScript

- -

この JavaScript は、 HTML 属性の値が JavaScript オブジェクトのプロパティの変更によって影響を受けないことを示しています。

- -
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>`);
- -

結果

- -

{{ EmbedLiveSample('HTML_onevent_attributes', '', '', '', 'Web/Guide/Events/Event_handlers') }}

- -

歴史的な理由から、{{HTMLElement("body")}} および {{HTMLElement("frameset")}} 要素の一部の属性/プロパティは、実際にはその親 {{domxref("Window")}} オブジェクトにイベントハンドラーを設定します。(HTML 仕様はこれらを {{domxref("GlobalEventHandlers/onblur", "onblur")}}, {{domxref("GlobalEventHandlers/onerror", "onerror")}}, {{domxref("GlobalEventHandlers/onfocus", "onfocus")}}, {{domxref("GlobalEventHandlers/onload", "onload")}}, {{domxref("GlobalEventHandlers/onscroll", "onscroll")}} と命名しています。)

- -

イベントハンドラーの引数、this の結びつけ、および返値

- -

イベントハンドラーが HTML 属性として指定されている場合、指定されたコードは次の引数を持つ関数にラップされます。

- -
    -
  • event - {domxref("GlobalEventHandlers.onerror", "onerror")}} を除くすべてのイベントハンドラー。
  • -
  • event, source, lineno, colno, error - {{domxref("GlobalEventHandlers.onerror", "onerror")}} のイベントハンドラー。なお、 event 引数には、実際にはエラーメッセージが文字列として含まれています。
  • -
- -

イベントハンドラーが呼び出されると、ハンドラー内の this キーワードは、ハンドラーが登録されている DOM 要素に設定されます。詳しくは、this キーワードのドキュメントを参照してください。

- -

ハンドラーからの返値は、イベントが取り消されるかどうかを決定します。返値値の具体的な処理はイベントの種類によって異なります。詳細については、HTML 仕様の「イベントハンドラー処理アルゴリズム」を参照してください。

- -

イベントハンドラーが呼び出されたとき

- -
-

作成中 (非捕獲リスナー)

-
- -

用語集

- -

イベントハンドラーという用語は、次のように使用されます。

- -
    -
  • イベントの通知を受けるように登録されている関数またはオブジェクト
  • -
  • または、より具体的には、<button onclick="alert(this)">window.onload = function() { … }など、HTML の on… 属性または Web API のプロパティを介してイベントリスナーを登録するメカニズム。
  • -
- -

イベントを待ち受けするためのさまざまな方法を議論するときは、

- -
    -
  • イベントリスナーは、{{domxref("EventTarget.addEventListener()")}} によって登録された関数またはオブジェクトを参照します。
  • -
  • 一方、イベントハンドラーon... 属性またはプロパティを介して登録された関数を指します。
  • -
- -

仕様書

- - - - - - - - - - - - - - - - - - - - - -
仕様書状態備考
{{SpecName('HTML WHATWG', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML5 W3C')}}
- -

ブラウザーの互換性

- -

イベントハンドラープロパティが存在することの検出

- -

JavaScript の {{jsxref("Operators/in", "in")}} 演算子でイベントハンドラープロパティの存在を検出することができます。例えば、以下のようになります。

- -
if ("onsomenewfeature" in window) {
-  /* do something amazing */
-}
-
- -

イベントハンドラーとプロトタイプ

- -

DOM プロトタイプオブジェクトには、IDL で定義された属性の値を設定したり、アクセスしたりすることはできません。つまり、例えば Window.prototype.onload を変更することはできません。以前は、 Gecko では イベントハンドラー (onload など) が IDL 属性として実装されていなかったので可能だったのですが、現在はできなくなりました。これにより互換性が向上します。

diff --git a/files/ja/web/guide/events/index.html b/files/ja/web/guide/events/index.html deleted file mode 100644 index d05127c86a..0000000000 --- a/files/ja/web/guide/events/index.html +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: イベント開発者ガイド -slug: Web/Guide/Events -tags: - - DOM - - Event - - Guide - - events -translation_of: Web/Guide/Events ---- -
{{draft()}}
- -

イベントは、ウェブページの生存期間に起こる様々な出来事を非同期に扱うために使用されるデザインパターンと、さまざまな種類の多数の出来事についての名前、特性付け、利用の両方を指します。

- -

概要ページでは、デザインパターンの紹介と最近のウェブブラウザーで定義され行われる出来事の種類の概要を提供します。

- -

カスタムイベントページでは、独自コードでイベントコードのデザインパターンを使用して、ユーザーオブジェクトによって発行される新しいイベント型を定義し、それらのイベントを処理するためのリスナー関数を登録し、ユーザーのコードでイベントを発生させる方法について説明します。

- -

その他のページでは、ウェブブラウザーで定義されているさまざまな種類のイベントの使用方法について説明します。残念なことに、これらのイベントはウェブブラウザーの進化に合わせて部分的に定義されてきたため、最新のウェブブラウザーに組み込まれている、または定義されているイベントの満足のいく体系的な特徴付けはありません。

- -

ウェブブラウザーが実行されている端末は、例えば実世界での場所や方向の変化によってイベントが発生することがあり、これは方向座標系上のページおよび三次元変換の使用上のページで部分的に説明されているとおりです。これは端末の縦の方向が変化した場合とは異なりますが、似ています。

- -

ブラウザーが表示されるウィンドウがイベントを発生させることがあります。例えば、ユーザーがウィンドウを最大化したり、その他の変更があったりすると、サイズ変更イベントが発生します。

- -

ウェブページを読み込んでいるプロセスがユーザーに表示するためにウェブページをダウンロードし、解析し、レンダリングする様々な段階を補完するための応答としてイベントを発生することがあります。

- -

ウェブページのコンテンツへのユーザーの操作がイベントを発生させることがあります。ユーザーの操作によって発生したイベントは、ブラウザー設計の初期の頃に進化し、イベントが呼び出される順序およびその順序を制御することができる方法を定義する複雑なシステムを含んでいます。さまざまな種類のユーザー対話型イベントには、以下のものがあります。

- - - -

構造面やコンテンツにおけるウェブページの変更が、いくつかのイベントを発生させることがあり、変化イベントのページで説明されているとおりですが、これらのイベントはより軽い Mutation Observer のアプローチに置き換えられて非推奨になっています。

- -

HTML 文書に埋め込まれたメディアストリームがいくつかのイベントを発生させることがあり、メディアイベントページで説明されている通りです。

- -

ウェブページによって行われるネットワークリクエストが、いくつかのイベントを発生させることがあります。

- -

他にも、ウェブブラウザーが定義したイベントの発生源で、このガイドではまだ言及していないものがたくさんあります。

- -
-

メモ: このイベント開発者ガイドは継続的な作業が必要です。構造を再編したりページを書き直したりする必要があります。イベントについて知っておくことが必要なすべてをここで提供できるようになりたいと考えています。

-
- -

文書

- -

{{LandingPageListSubpages}}

diff --git a/files/ja/web/guide/events/orientation_and_motion_data_explained/index.html b/files/ja/web/guide/events/orientation_and_motion_data_explained/index.html deleted file mode 100644 index 467800a0d6..0000000000 --- a/files/ja/web/guide/events/orientation_and_motion_data_explained/index.html +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: 方向および動きとして示されるデータ -slug: Web/Guide/Events/Orientation_and_motion_data_explained -tags: - - DOM - - Mobile - - Motion - - NeedsContent - - Orientation - - Responsive Design - - páginas_a_traducir - - rotation -translation_of: Web/Guide/Events/Orientation_and_motion_data_explained ---- -

{{ Draft() }}

-

方向や動きのイベントを使用するときは、ブラウザから与えられる値の意味を理解することが重要です。この記事では操作時の座標システムに関する詳細情報と、それらの使い方を説明します。

-

座標フレームについて

-

{{原語併記("座標フレーム", "coordinate frame")}} は、オブジェクトに関する 3 軸 (X、Y、Z) の方向が定義されているシステムです。方向や動きのイベントを使用するときに考慮する座標フレームは 2 つあります:

-

地球座標フレーム

-

{{原語併記("地球座標フレーム", "Earth coordinate frame")}} は、地球の中心に固定されている座標フレームです。すなわち、軸は重力によって引かれる力および標準的な磁北方向に基づいて揃えられます。私たちは大文字 ("X"、"Y"、"Z") を、地球座標フレームの軸を示すために使用します。

-
    -
  • X 軸は地面に沿ってたどり、Y 軸と直交します。また、軸の正の方向が東を指します (従って、負の方向は西を指します)。
  • -
  • Y 軸は地面に沿ってたどり、正の方向が真北 (すなわち北極であり、磁北ではありません) を、負の方向が真南を指します。
  • -
  • Z 軸は地面に直交します。これは、デバイスと地球の中心との間に引かれた線と考えてください。Z 座標の値は正の方向が上向き (地球の中心から遠ざかる)、負の方向が下向き (地球の中心に向かう) です。
  • -
-

デバイス座標フレーム

-

{{原語併記("デバイス座標フレーム", "Device coordinate frame")}} は、デバイスの中心に固定された座標フレームです。私たちは小文字 ("x"、"y"、"z") を、デバイス座標フレームの軸を示すために使用します。

-

axes.png

-
    -
  • x 軸はスクリーンの水平面にあり、正の方向が右を、負の方向が左を指します。
  • -
  • y 軸はスクリーンの水平面にあり、正の方向が上端側を、負の方向が下端側を指します。
  • -
  • z 軸はスクリーンやキーボードに直交しており、正の方向がスクリーンから外側へ伸びていきます。
  • -
-
- 注意: 電話機やタブレットでは、デバイスの方向が常にスクリーンの標準的な方向に対して考えられます。これは、ほとんどのデバイスで "ポートレート" 方向になります。ラップトップコンピュータでは、方向はキーボードに対して考えられます。補正するためにデバイスの方向の変化を検知したい場合は、orientationchange イベントを使用できます。
-

回転について

-

回転は、デバイス座標フレームと地球座標フレームとの度合いの違いという点から各軸で表現され、またそれは度単位で測られます

-

Alpha

-

z 軸を中心にした回転、すなわちデバイスをひねるようにすると、alpha 回転角が変化します:

-

alpha.png

-

alpha 角はデバイスの上端が地球の北極をまっすぐ向いているときが 0 度であり、デバイスが左へ回転するのに従って増加します。

-

Beta

-

x 軸を中心にした回転、すなわちデバイスを向こう側やユーザ側へ向かって傾けると、beta 回転角が変化します:

-

beta.png

-

beta 角はデバイスの上端および下端から地球の表面までの距離がどちらも同じであるときが 0 度であり、デバイスを前方へ傾けるのに従って 180 度まで増加、後方へ傾けるのに従って -180 度まで減少します。

-

Gamma

-

y 軸を中心にした回転、すなわちデバイスを左右に傾けると、gamma 回転角が変化します:

-

gamma.png

-

gamma 角はデバイスの左端および右端から地球の表面までの距離がどちらも同じであるときが 0 度であり、デバイスを右へ傾けるのに従って 90 度まで増加、左へ傾けるのに従って -90 度まで減少します。

diff --git a/files/ja/web/guide/events/overview_of_events_and_handlers/index.html b/files/ja/web/guide/events/overview_of_events_and_handlers/index.html deleted file mode 100644 index 0a52f3b4c6..0000000000 --- a/files/ja/web/guide/events/overview_of_events_and_handlers/index.html +++ /dev/null @@ -1,136 +0,0 @@ ---- -title: Overview of Events and Handlers -slug: Web/Guide/Events/Overview_of_Events_and_Handlers -translation_of: Web/Guide/Events/Overview_of_Events_and_Handlers ---- -
-

This overview of events and event handling explains the code design pattern used to react to incidents occurring when a browser accesses a web page, and it summarizes the types of such incidents modern web browsers can handle.

-
- -

Events and event handling provide a core technique in JavaScript for reacting to incidents occurring when a browser accesses a web page, including events from preparing a web page for display, from interacting with the content of the web page,  relating to the device on which the browser is running, and from many other causes such as media stream playback or animation timing.

- -

Events and event handling become central to web programming with the addition of the language to browsers, accompanying a switch in the rendering architecture of browsers from fetch and load page rendering to event driven, reflow based, page rendering. Initially, browsers wait, until they receive all of the resources associated with a page, to parse, process, draw, and present the page to the user. The displayed page remains unchanged until the browser requests a new page. 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 e.g., downloads an image that can now be drawn on the screen, the completion of parsing a resource by the browser e.g., processes the HTML content of a page, the interaction of a user with the contents of the page e.g., clicks a button. Douglas Crockford explains this change effectively in several lectures, notably his talk, An Inconvenient API: The Theory of the DOM, which shows the change in flow from the original browser flow

- -
A comparison of the sequential and event-driven browser load sequences.
- -

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 this one.) Currently, all execution environments for JavaScript code use events and event handling.

- -

The event design pattern

- -

The event system, at its core, is simply a programming design pattern. The pattern starts with an agreement over a kind of event and:

- -
    -
  • the name String used for the event,
  • -
  • the type of the data structure used to represent the key properties of that event, and
  • -
  • the JavaScript object which will 'emit' that event.
  • -
- -

The pattern is implemented by

- -
    -
  • defining a JavaScript function which takes as an argument the data structure which was agreed upon, and
  • -
  • registering the function using the name String with the object which will emit the event.
  • -
- -

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 article on custom events. The pattern is also used by modern web browsers which define many events emitted in response to user input or browser activity.

- -

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 EventPrototype object. Browsers use as the registration method for the function which will handle those data structures a method called addEventListener 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.

- -

Button Event Handler Demo

- -

For example, browser button elements are intended to emit events named 'click' 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 button as:

- -
<button id="buttonOne">Click here to emit a 'click' event</button>
- -

and, in our JavaScript code, we could first define a function to listen to that 'click' event:

- -
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 );
-};
- -

and second register our function with the the Button object, either on the scripting side using the DOM (Document Object Model) representation of the HTML page:

- -
var buttonDOMElement = document.querySelector('#buttonOne');
-buttonDOMElement.addEventListener('click', example_click_handler);
- -

or within the HTML page by adding the function as the value of the 'onclick' attribute, although this second approach is usually only used in very simple web pages.

- -

{{ EmbedLiveSample('Button_Event_Handler') }}

- -

This code relies on the agreement that there is a kind of event called 'click' which will call any listener (or 'handler') function with an Event object argument (actually, in this case a derivative MouseEvent object) and which will be fired by HTML button 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 buttonDOMElement JavaScript object would call the example_click_handler function with an Event 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 ev object since it is passed as an argument; the object has information about the event, notably the time at which the event occurred.

- -

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:

- -
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);
-
- -

so that this code will only be executed after the document object emits the 'DOMContentLoaded' 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.

- -

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.

- -

Notable events

- -

Web browsers define a large number of events so it is not practical to list them all. The Event Reference attempts to maintain a list of the standard Events used in modern web browsers.

- -

In general, we can distinguish events of different kinds based on the object emitting the event including:

- -
    -
  • the window object, such as due to resizing the browser,
  • -
  • the window.screen object, such as due to changes in device orientation,
  • -
  • the document object, including the loading, modification, user interaction, and unloading of the page,
  • -
  • the objects in the DOM (document object model) tree including user interactions or modifications,
  • -
  • the XMLHttpRequest objects used for network requests, and
  • -
  • the media objects such as audio and video, when the media stream players change state.
  • -
- -

although this list is currently incomplete.

- -

Some notable events are:

- -
-

Note: 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 this web page or in this Stack Overflow question.

-
- -
    -
  • the global object window emits an event called 'load' 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,
  • -
  • the global object window emits an event called 'resize' when the height or the width of the browser window is changed by a user,
  • -
  • the DOM object document representing the HTML document emits an event called 'DOMContentLoaded' when the document has finished loading,
  • -
  • the DOM node objects such as div or button emit an event called 'click' when the user presses the mouse button while the mouse pointer is on top of the DOM node in the HTML page.
  • -
- -

 

- -

The Event object hierarchy

- -

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 EventPrototype object.

- -

A partial diagram of the class hierarchy of event objects is:

- -
-

Note: This diagram is incomplete.

-
- -

- -

The Web API Documentation contains a page defining the Event object which also includes the known DOM event subclasses of the Event object.

- -

Documents

- -

Three sources on the MDN (Mozilla Developer Network) web site are particularly useful for programmers wanting to work with events:

- - - -

 

- -

 

- -

 

diff --git a/files/ko/_redirects.txt b/files/ko/_redirects.txt index b0905fe764..306d13b6fa 100644 --- a/files/ko/_redirects.txt +++ b/files/ko/_redirects.txt @@ -627,6 +627,7 @@ /ko/docs/Using_the_Mozilla_JavaScript_interface_to_XSL_Transformations /ko/docs/Web/XSLT/Using_the_Mozilla_JavaScript_interface_to_XSL_Transformations /ko/docs/Web/API/Boolean /ko/docs/Web/JavaScript/Reference/Global_Objects/Boolean /ko/docs/Web/API/Canvas_API/캔버스_튜토리얼 /ko/docs/Web/API/Canvas_API/Tutorial +/ko/docs/Web/API/Detecting_device_orientation /ko/docs/orphaned/Web/API/Detecting_device_orientation /ko/docs/Web/API/Document/defaultView/popstate_event /ko/docs/Web/API/Window/popstate_event /ko/docs/Web/API/Document/defaultView/resize_event /ko/docs/Web/API/Window/resize_event /ko/docs/Web/API/Document/drag_이벤트 /ko/docs/Web/API/Document/drag_event @@ -634,6 +635,7 @@ /ko/docs/Web/API/DocumentOrShadowRoot/activeElement /ko/docs/Web/API/Document/activeElement /ko/docs/Web/API/DocumentOrShadowRoot/getSelection /ko/docs/Web/API/Document/getSelection /ko/docs/Web/API/DocumentOrShadowRoot/styleSheets /ko/docs/Web/API/Document/styleSheets +/ko/docs/Web/API/Document_Object_Model/Events /ko/docs/orphaned/Web/API/Document_Object_Model/Events /ko/docs/Web/API/Document_Object_Model/Preface /ko/docs/Web/API/Document_Object_Model /ko/docs/Web/API/Document_Object_Model/소개 /ko/docs/Web/API/Document_Object_Model/Introduction /ko/docs/Web/API/Document_Object_Model/예제 /ko/docs/Web/API/Document_Object_Model/Examples @@ -803,7 +805,9 @@ /ko/docs/Web/Guide/CSS/Visual_formatting_model /ko/docs/Web/CSS/Visual_formatting_model /ko/docs/Web/Guide/DOM /ko/docs/conflicting/Web/API/Document_Object_Model /ko/docs/Web/Guide/DOM/Using_full_screen_mode /ko/docs/Web/API/Fullscreen_API +/ko/docs/Web/Guide/Events /ko/docs/orphaned/Web/Guide/Events /ko/docs/Web/Guide/Events/Creating_and_triggering_events /ko/docs/orphaned/Web/Guide/Events/Creating_and_triggering_events +/ko/docs/Web/Guide/Events/Overview_of_Events_and_Handlers /ko/docs/orphaned/Web/Guide/Events/Overview_of_Events_and_Handlers /ko/docs/Web/Guide/HTML /ko/docs/Learn/HTML /ko/docs/Web/Guide/HTML/Content_Editable /ko/docs/Web/Guide/HTML/Editable_content /ko/docs/Web/Guide/HTML/컨텐트_카테고리 /ko/docs/Web/Guide/HTML/Content_categories @@ -1038,7 +1042,7 @@ /ko/docs/Web/참조/API /ko/docs/Web/Reference/API /ko/docs/WebAPI /ko/docs/conflicting/Web/API /ko/docs/WebAPI/Battery_Status /ko/docs/Web/API/Battery_Status_API -/ko/docs/WebAPI/Detecting_device_orientation /ko/docs/Web/API/Detecting_device_orientation +/ko/docs/WebAPI/Detecting_device_orientation /ko/docs/orphaned/Web/API/Detecting_device_orientation /ko/docs/WebAPI/Managing_screen_orientation /ko/docs/Web/API/CSS_Object_Model/Managing_screen_orientation /ko/docs/WebAPI/Network_Information /ko/docs/Web/API/Network_Information_API /ko/docs/WebAPI/Proximity /ko/docs/Web/API/Proximity_Events diff --git a/files/ko/_wikihistory.json b/files/ko/_wikihistory.json index cb8b655ecf..6e5d3b301d 100644 --- a/files/ko/_wikihistory.json +++ b/files/ko/_wikihistory.json @@ -3637,12 +3637,6 @@ "Channy" ] }, - "Web/API/Document_Object_Model/Events": { - "modified": "2020-12-01T12:09:06.517Z", - "contributors": [ - "dink95" - ] - }, "Web/API/Document_Object_Model/Examples": { "modified": "2020-05-26T14:45:03.340Z", "contributors": [ @@ -8834,18 +8828,6 @@ "corps99" ] }, - "Web/Guide/Events": { - "modified": "2019-03-23T23:03:35.888Z", - "contributors": [ - "moolow" - ] - }, - "Web/Guide/Events/Overview_of_Events_and_Handlers": { - "modified": "2019-03-23T22:48:26.046Z", - "contributors": [ - "PineMt" - ] - }, "Web/Guide/HTML/Content_categories": { "modified": "2020-07-29T11:16:44.120Z", "contributors": [ @@ -17981,14 +17963,6 @@ "oohii" ] }, - "Web/API/Detecting_device_orientation": { - "modified": "2019-03-23T23:27:06.270Z", - "contributors": [ - "ingpdw", - "PillarLee", - "junho85" - ] - }, "Web/API/CSS_Object_Model/Managing_screen_orientation": { "modified": "2019-03-23T23:27:05.980Z", "contributors": [ @@ -18704,5 +18678,31 @@ "contributors": [ "cs09g" ] + }, + "orphaned/Web/API/Detecting_device_orientation": { + "modified": "2019-03-23T23:27:06.270Z", + "contributors": [ + "ingpdw", + "PillarLee", + "junho85" + ] + }, + "orphaned/Web/API/Document_Object_Model/Events": { + "modified": "2020-12-01T12:09:06.517Z", + "contributors": [ + "dink95" + ] + }, + "orphaned/Web/Guide/Events": { + "modified": "2019-03-23T23:03:35.888Z", + "contributors": [ + "moolow" + ] + }, + "orphaned/Web/Guide/Events/Overview_of_Events_and_Handlers": { + "modified": "2019-03-23T22:48:26.046Z", + "contributors": [ + "PineMt" + ] } } \ No newline at end of file diff --git a/files/ko/orphaned/web/api/detecting_device_orientation/index.html b/files/ko/orphaned/web/api/detecting_device_orientation/index.html new file mode 100644 index 0000000000..1fd9fe3e91 --- /dev/null +++ b/files/ko/orphaned/web/api/detecting_device_orientation/index.html @@ -0,0 +1,274 @@ +--- +title: 기기 방향 감지하기 +slug: orphaned/Web/API/Detecting_device_orientation +translation_of: Web/API/Detecting_device_orientation +original_slug: Web/API/Detecting_device_orientation +--- +
{{SeeCompatTable}}
+ +

요약

+ +

웹을 이용 가능한 기기들은 자신들의 방향을 알 수 있게 되었다. 즉, 중력과의 관계에서 자신의 방향의 변화를 나타내는 데이터를 알 수 있다는 뜻이다. 특히, 휴대 전화와 같이 손에 쥐고 쓸 수 있는 기기들은 이 정보를 화면을 수직으로 유지하기 위해 자동으로 회전시키는데 사용할 수 있고, 기기가 회전되어서 폭이 높이보다 길 때는 와이드 스크린으로 표시할 수 있게 된다.

+ +

방향 정보를 다루는 두 가지 방법의 JavaScript 이벤트가 있다. 첫 번째는 {{domxref("DeviceOrientationEvent")}}로 가속도계가 기기의 방향의 변화를 감지했을 때 발생한다.  이 방향 이벤트들에 의해 보고되는 데이터를 받아서 처리함으로써, 사용자들이 기기를 움직이여서 생기는 방향과 높이의 변화를 상호 작용적으로 응답할 수 있게 된다.

+ +

두 번째 이벤트는 {{domxref("DeviceMotionEvent")}}로 가속도에 변화가 일어났을 때 발생한다. 이 이벤트는 {{domxref("DeviceOrientationEvent")}}와는 방향이 아닌 가속도를 감지하고 있다는 점에서 다르다. 일반적으로{{domxref("DeviceMotionEvent")}}를 감지할 수 있는 센서들은 저장 장치들을 충격으로부터 보호하기 위해 노트북에서 사용되는 센서들을 포함한다. {{domxref("DeviceOrientationEvent")}}는 모바일 기기에서 주로 더 많이 나타난다.

+ +

방향 이벤트 처리하기

+ +

방향의 변화를 받기 위해 여러분이 해야하는 것은 {{ event("deviceorientation") }} 이벤트에 리스너를 등록하는 것 뿐이다:

+ +
window.addEventListener("deviceorientation", handleOrientation, true);
+
+ +

이벤트 리스너를 등록한 후에는 (여기에서는 JavaScript 함수 handleOrientation()), 리스너 함수가 업데이트 된 방향 데이터와 함께 주기적으로 호출된다.

+ +

방향 이벤트는 다음 네 개의 값을 가진다:

+ +
    +
  • {{ domxref("DeviceOrientationEvent.absolute") }}
  • +
  • {{ domxref("DeviceOrientationEvent.alpha") }}
  • +
  • {{ domxref("DeviceOrientationEvent.beta") }}
  • +
  • {{ domxref("DeviceOrientationEvent.gamma") }}
  • +
+ +

이벤트 핸들러 함수는 보통 다음과 같다:

+ +
function handleOrientation(event) {
+  var absolute = event.absolute;
+  var alpha    = event.alpha;
+  var beta     = event.beta;
+  var gamma    = event.gamma;
+
+  // Do stuff with the new orientation data
+}
+
+ +

방향 값 설명

+ +

각 축으로부터 보고된 값은 표준 좌표계 축을 중심으로 회전한 양을 가리킨다. 더 자세한 내용은 Orientation and motion data explained 문서에 나와있으며, 다음은 이를 간략하게 요약한 것이다.

+ +
    +
  • {{ domxref("DeviceOrientationEvent.alpha") }} 값은 0도부터 360도까지 범위의 z축을 중심으로 한 기기의 움직임을 나타낸다.
  • +
  • {{ domxref("DeviceOrientationEvent.beta") }} 값은 -180도부터 180도까지 범위의 x축을 줌심으로 한 기기의 움직임을 나타낸다. 이는 기기의 앞뒤 움직임을 나타낸다.
  • +
  • {{ domxref("DeviceOrientationEvent.gamma") }} 값은 -90도부터 90도까지 범위의 y축을 중심으로 한 기기의 움직임을 나타낸다. 이는 기기의 좌우 움직임을 나타낸다.
  • +
+ +

방향 예제

+ +

이 예제는 {{event("deviceorientation")}} 이벤트를 지원하고 방향을 감지할 수 있는 기기에서 실행중인 모든 브라우저에서 작동한다.

+ +

자 그럼, 정원에 공이 하나 있다고 상상해보자:

+ +
<div class="garden">
+  <div class="ball"></div>
+</div>
+
+<pre class="output"></pre>
+
+ +

이 정원은 가로 세로 200 픽셀이고(그렇다, 작은 정원이다), 정 중앙에 공이 있다:

+ +
.garden {
+  position: relative;
+  width : 200px;
+  height: 200px;
+  border: 5px solid #CCC;
+  border-radius: 10px;
+}
+
+.ball {
+  position: absolute;
+  top   : 90px;
+  left  : 90px;
+  width : 20px;
+  height: 20px;
+  background: green;
+  border-radius: 100%;
+}
+
+ +

이제, 우리가 기기를 움직이면 공도 따라서 움직일 것이다:

+ +
var ball   = document.querySelector('.ball');
+var garden = document.querySelector('.garden');
+var output = document.querySelector('.output');
+
+var maxX = garden.clientWidth  - ball.clientWidth;
+var maxY = garden.clientHeight - ball.clientHeight;
+
+function handleOrientation(event) {
+  var x = event.beta;  // In degree in the range [-180,180]
+  var y = event.gamma; // In degree in the range [-90,90]
+
+  output.innerHTML  = "beta : " + x + "\n";
+  output.innerHTML += "gamma: " + y + "\n";
+
+  // Because we don't want to have the device upside down
+  // We constrain the x value to the range [-90,90]
+  if (x >  90) { x =  90};
+  if (x < -90) { x = -90};
+
+  // To make computation easier we shift the range of
+  // x and y to [0,180]
+  x += 90;
+  y += 90;
+
+  // 10 is half the size of the ball
+  // It center the positionning point to the center of the ball
+  ball.style.top  = (maxX*x/180 - 10) + "px";
+  ball.style.left = (maxY*y/180 - 10) + "px";
+}
+
+window.addEventListener('deviceorientation', handleOrientation);
+
+ +

여기 실제로 실행해 볼 수 있는 예제이다:

+ +
{{ EmbedLiveSample('Orientation_example', '230', '260') }}
+ +
+

경고: Chrome과 Firefox는 동일한 방식으로 각을 다루지 않습니다. 그래서 어떤 축의 방향은 반대가 됩니다.

+
+ +

모션 이벤트 처리하기

+ +

모션 이벤트는 이벤트 이름이 {{ event("devicemotion") }}으로 다르다는 점을 제외하면, 방향 이벤트를 처리하는 방법과 동일하다.

+ +
window.addEventListener("devicemotion", handleMotion, true);
+ +

HandleMotion 함수의 파라미터로 넘겨진 {{ domxref("DeviceMotionEvent") }} 객체에 실제로 변화된 정보들이 담겨져 있다.

+ +

모션 이벤트는 다음 네 가지 속성을 가진다:

+ +
    +
  • {{ domxref("DeviceMotionEvent.acceleration") }}
  • +
  • {{ domxref("DeviceMotionEvent.accelerationIncludingGravity") }}
  • +
  • {{ domxref("DeviceMotionEvent.rotationRate") }}
  • +
  • {{ domxref("DeviceMotionEvent.interval") }}
  • +
+ +

모션 값 설명

+ +

{{ domxref("DeviceMotionEvent") }} 객체는 웹 개발자들에게 기기의 위치와 방향의 변화 속도에 관한 정보를 제공한다. 세 개의 축에 따라 변화한 정보가 제공된다 (자세한 내용은 Orientation and motion data explained 문서를 참조).

+ +

{{domxref("DeviceMotionEvent.acceleration","acceleration")}}과 {{domxref("DeviceMotionEvent.accelerationIncludingGravity","accelerationIncludingGravity")}}에서, 각 축은 다음에 해당된다:

+ +
    +
  • x: 서쪽에서 동쪽으로 나타나는 축을 의미한다
  • +
  • y: 남쪽에서 북쪽으로 나타나는 축을 의미한다
  • +
  • z: 땅에서 수직으로 나타나는 축을 의미한다
  • +
+ +

{{domxref("DeviceMotionEvent.rotationRate","rotationRate")}}에서, 조금은 다르게, 각 값들은 다음에 해당된다:

+ +
    +
  • alpha: 화면(또는 데스크탑의 키보드)에 수직인 축을 따른 회전율을 의미한다
  • +
  • beta: 화면(또는 데스크탑의 키보드)의 평면의 왼쪽에서 오른쪽으로 나타나는 축을 따른 회전율을 의미한다
  • +
  • gamma: 화면(또는 데스크탑의 키보드)의 평면의 아래에서 위쪽으로 나타나는 축을 따른 회전율을 의미한다
  • +
+ +

마지막으로, {{domxref("DeviceMotionEvent.interval","interval")}}은 기기에서 데이터를 얻을 수 있는 시간 간격(단위는 밀리초)을 의미한다.

+ +

스펙

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Device Orientation')}}{{Spec2('Device Orientation')}}Initial specification.
+ +

브라우저 호환성

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
{{domxref("DeviceOrientationEvent")}}7.03.6[1]
+ 6
{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
{{domxref("DeviceMotionEvent")}}{{ CompatVersionUnknown() }}6{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
{{domxref("DeviceOrientationEvent")}}3.03.6[1]
+ 6
{{ CompatNo() }}{{ CompatNo() }}4.2
{{domxref("DeviceMotionEvent")}}{{ CompatVersionUnknown() }}6{{ CompatUnknown() }}{{ CompatUnknown() }}4.2
+
+ +

Gecko 구현 참고 사항

+ +
    +
  1. Firefox 3.6, 4, 5는 표준인 {{domxref("DeviceOrientationEvent")}} 이벤트가 아닌 mozOrientation 을 지원한다
  2. +
+ +

참고 자료

+ + diff --git a/files/ko/orphaned/web/api/document_object_model/events/index.html b/files/ko/orphaned/web/api/document_object_model/events/index.html new file mode 100644 index 0000000000..84152bbfbc --- /dev/null +++ b/files/ko/orphaned/web/api/document_object_model/events/index.html @@ -0,0 +1,85 @@ +--- +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 +--- +
{{DefaultAPISidebar("DOM")}}
+ +

소개

+ +

이 장에서는 DOM 이벤트 모델을 설명한다.  Event 인터페이스는 DOM의 노드에서 이벤트 등록 및  event listeners를 위한 인터페이스와 더불어 다양한 이벤트 인터페이스가 서로 어떻게 관련되는지 보여주는 몇 가지 더 긴 예와 함께 설명된다.

+ +

There is an excellent diagram that clearly explains the three phases of event flow through the DOM in the DOM Level 3 Events draft.

+ +

Also see Example 5: Event Propagation in the Examples chapter for a more detailed example of how events move through the DOM.

+ +

Event listener등록

+ +

DOM 요소에 대한 이벤트 핸들러를 등록하는 방법에는 3가지가 있다.

+ +

{{domxref("EventTarget.addEventListener")}}

+ +
// 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')
+}
+
+ +

이 방식은 근대의 웹페이지에서 사용해야하는 방법이다.

+ +
+

Note: Internet Explorer 6–8 didn't support this method, offering a similar {{domxref("EventTarget.attachEvent")}} API instead. For cross-browser compatibility, use one of the many JavaScript libraries available.

+
+ +

더 자세한 내용은{{domxref("EventTarget.addEventListener")}}를 참조하세요.

+ +

HTML 속성

+ +
<button onclick="alert('Hello world!')">
+
+ +

속성에서 JavaScript 코드는 이벤트 매개변수를 통해 이벤트 객체를 통과합니다. 반환 값은 HTML 사양에 설명된 특별한 방법으로 처리됩니다.

+ +
+

경고: 이 방법은 피해야 합니다! 그것은 마크업을 부풀리고, 읽기 어렵게 만듭니다. 내용/구조와 행동에 대한 우려는 잘 분리되어 있지 않아 버그를 찾기가 더 어려워집니다.

+
+ +

DOM 요소 특성

+ +
// Assuming myButton is a button element
+myButton.onclick = function(event){alert('Hello world')}
+
+ +

The function can be defined to take an event parameter. The return value is treated in a special way, described in the HTML specification.

+ +

The problem with this method is that only one handler can be set per element and per event.

+ +

Accessing Event interfaces

+ +

Event handlers may be attached to various objects (including DOM elements, document, the {{domxref("window")}} object, etc.). When an event occurs, an event object is created and passed sequentially to the event listeners.

+ +

The {{domxref("Event")}} interface is accessible from within the handler function, via the event object passed as the first argument. The following simple example shows how an event object is passed to the event handler function, and can be used from within one such function.

+ +
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
+
+ + + + diff --git a/files/ko/orphaned/web/guide/events/index.html b/files/ko/orphaned/web/guide/events/index.html new file mode 100644 index 0000000000..596c7f932d --- /dev/null +++ b/files/ko/orphaned/web/guide/events/index.html @@ -0,0 +1,52 @@ +--- +title: Event developer guide +slug: orphaned/Web/Guide/Events +tags: + - DOM + - Event + - Guide + - NeedsUpdate + - events +translation_of: Web/Guide/Events +original_slug: Web/Guide/Events +--- +

{{draft()}}

+ +

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.

+ +

The overview page 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.

+ +

The custom events page 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.

+ +

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.

+ +

The device 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 page on orientation coordinate systems and the page on the use of 3D transforms. That is different, but similar, to the change in device vertical orientation. 

+ +

The window in which the browser is displayed which might trigger events, for example, change size if the user maximizes the window or otherwise changes it.

+ +

The process 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.

+ +

The user interaction 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:

+ + + +

The modification of the web page in structure or content might trigger some events, as is explained in the mutation events page, but the use of these events has been deprecated in favour of the lighter Mutation Observer approach.

+ +

The media streams embedded in the HTML documents might trigger some events, as explained in the media events page.

+ +

The network requests made by a web page might trigger some events.

+ +

There are many other sources of events defined by web browsers for which pages are not yet available in this guide.

+ +
+

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.

+
+ +

Docs

+ +

{{LandingPageListSubpages}}

diff --git a/files/ko/orphaned/web/guide/events/overview_of_events_and_handlers/index.html b/files/ko/orphaned/web/guide/events/overview_of_events_and_handlers/index.html new file mode 100644 index 0000000000..3690555d42 --- /dev/null +++ b/files/ko/orphaned/web/guide/events/overview_of_events_and_handlers/index.html @@ -0,0 +1,143 @@ +--- +title: Overview of Events and 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 +--- +
+

 이 글은 이벤트 및 이벤트 핸들링(event handling)에 대한 개요로서, 웹 페이지가 열려있는 동안 일어나는 사건(incident)에 대해 반응할 수 있도록 하는 코드 설계 패턴에 대해 설명하고, 현 세대의 웹 브라우저에서 핸들링할 수 있는 사건의 종류에 대해 요약한다.

+
+ +

 이벤트와 이벤트 핸들링은 웹 페이지가 사용자에 의해 열린 상태를 유지하는 동안 일어나는 사건에 대한 반응을 구현하기 위한 자바스크립트의 핵심적인 기술이다. 이러한 사건에는 페이지가 전시(display)되기 위한 준비과정 중 일어나는 사건, 웹 페이지상의 컨텐츠와 사용자의 상호작용에 의한 사건, 브라우저가 실행되는 기반 장치와 관련된 사건, 매체 스트림(media stream) 재생이나 애니메이션 시간 간격 등 기타 요인에 의한 사건 등이 있다.

+ +

 이벤트와 이벤트 핸들링은 자바스크립트가 처음 도입된 시점부터 중심적인 역할을 했으며, 이와 함께 브라우저의 렌더링 아키텍처 역시 단일 처리경로(single pass) 페이지 렌더링으로부터 리플로우(reflow) 기반, 이벤트 구동식(driven) 페이지 렌더링 개념으로 바뀌었다.

+ +

 최초에는 브라우저는 페이지의 모든 부분에 대한 문법분석(parse), 처리(process), 그리기(draw) 및 사용자에게 표현(present)까지의 모든 과정이 끝날 때까지 대기하고, 페이지 작업이 끝나면 그 상태로 바뀌지 않고 새 페이지 요청이 있어서 가져오기(fetch)작업이 일어나기 전까지는 그대로의 모습을 유지했다. 

+ +

 리플로우 기반 이벤트 구동식 페이지 렌더링 개념으로 바뀐 뒤에는 브라우저는 처리, 그리기, 컨텐츠 표현(present), 반복순환작업을 다시 개시하도록 하는 이벤트 트리거에 대한 대기 등의 작업을 반복순환(loop)하여 수행한다. 이 이벤트 트리거라는 것은 이벤트를 발생하게 하는 사건을 이르는 것으로서, 네트워크상의 자원 로드 완료( 예 : 이미지가 다운로드되어 화면상에 그릴 수 있게 됨), 브라우저에 의한 자원의 문법분석 완료( 예 : HTML페이지 처리가 끝남) 페이지의 컨텐츠와 사용자와의 상호작용(예 : 버튼을 클릭한다) 등이 이러한 사건이 될 수 있다.

+ +

 더글라스 크록포드는 An inconvenient API : The theory of the DOM(불편한 API : DOM의 이론)이라는 제목의 강연에서 이러한 변화를 여러 단원에 걸쳐 설명하였는데, 본래의 작업 흐름에서 이벤트 구동식 브라우저의 작업 흐름으로 바뀌는 것을 다음과 같이 보여주었다.

+ +
A comparison of the sequential and event-driven browser load sequences.
+ +

 두 번째 그림에 보이는 처리방식은 마지막 단계의 작업흐름을 변화시킴으로써 첫 번째 그림의 단일 경로 처리흐름에서 반복순환 흐름으로 바뀐 것을 보여준다. 두 번째 그림은 Paint작업이 끝나면 새로운 이벤트 발생에 대한 처리(이벤트 핸들링)를 하기 위해 이벤트를 기다리게 된다. 이 혁신적인 개념을 이용하면 자원을 다 획득하지 않았더라도 페이지를 부분적으로 렌더링하는 것이 가능하며, 최초에는 자바스크립트에 의해 발전된 이벤트 구동에 의한 동작 효과적으로 구현할 수 있다. (이 강의는 여기를 포함한 다양한 경로로 볼 수 있다) 현재 모든 자바스크립트 코드 실행 환경에서는 이벤트와 이벤트 핸들링을 사용한다.

+ +

이벤트 설계 패턴

+ +

이벤트 시스템은 근본적으로는 단순한 프로그래밍 설계 패턴이다. 이 패턴는 기본적으로 이벤트의 종류와 다음 사항에 대해 합의된 약속을 기반으로 한다.

+ +
    +
  • 각 이벤트를 가리키는 이벤트명 문자열
  • +
  • 각 이벤트의 핵심 프로퍼티를 나타내기 위한 자료구조의 형식
  • +
  • 각 이벤트를 발동할 자바스크립트 객체
  • +
+ +

패턴을 구현하기 위해서는 다음이 필요하다.

+ +
    +
  • 위에서 약속된 자료구조를 인수로 받는 자바스크립트 함수를 정의한다.
  • +
  • 이벤트를 발동할 객체에 약속된 해당 이벤트의 이벤트명을 사용하여 위의 함수를 등록한다.
  • +
+ +

이 함수는 리스너(listener) 또는 핸들러(handler)라는 혼용된 명칭으로 불린다. 이 패턴은 커스텀 이벤트에 관한 글에서 설명한 대로의 완전한 커스텀 이벤트를 사용하여 쉽게 구현할 수 있다. 이 패턴은 사용자 입력, 브라우저 활동 등에 의해 발동되는 다양한 이벤트를 정의하는 최신 웹 브라우저에서도 많이 사용한다.

+ +

 최신 웹 브라우저는 이 이벤트 패턴을 표준화된 방식으로 구현한다. 브라우저는 어떤 이벤트의 프로퍼티를 나타내는 자료 구조로서  EventPrototype 객체를 원천으로 하는 어떤 객체를 사용한다. 또한 이러한 자료구조를 핸들링할 함수에 대한 등록 메소드로서 addEventListener 메소드를 사용하는데 이것은 인수로서 이벤트명과 핸들러 함수를 받는다. 마지막으로 브라우저는 이벤트 발동자(emitter)로 수많은 객체를 정의하며 또한 이 객체들에 의해 생성되는 여러 이벤트형(event type)을 정의한다.

+ +

버튼 이벤트 핸들러 데모

+ +

하나의 예시로서 브라우저 button 요소(element)는 'click'이라는 이름의 이벤트를 마우스 클릭 또는 터치스크린의 경우 손가락 터치에 반응하여 발동시킨다. 버튼은 HTML 페이지에서 다음과 같이 정의할 수 있다.

+ +
<button id="buttonOne">Click here to emit a 'click' event</button>
+ +

그리고 자바스크립트 코드에서 'click' 이벤트에 대한 리스너로서의 함수, 즉 핸들러로 사용할 함수를 정의한다.

+ +
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 );
+};
+ +

그 다음 해당 Button 객체와 함께 위의 함수를 등록하는데, 첫 번째 방법은 HTML 페이지의 DOM(문서 객체 모델) 표현법을 이용하여 다음과 같이 스크립트상에서 나타내는 방법이다. 

+ +
var buttonDOMElement = document.querySelector('#buttonOne');
+buttonDOMElement.addEventListener('click', example_click_handler);
+ +

또 다른 방법은 HTML 페이지 상에서 'onclick' 애트리뷰트의 값으로 핸들러로 쓸 함수를 대입시키는 것인데, 보통 이 방식은 매우 단순한 웹 페이지에서나 쓰인다.

+ +

{{ EmbedLiveSample('Button_Event_Handler') }}

+ +

This code relies on the agreement that there is a kind of event called 'click' which will call any listener (or 'handler') function with an Event object argument (actually, in this case a derivative MouseEvent object) and which will be fired by HTML button 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 buttonDOMElement Javascript object would call the example_click_handler function with an Event 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 ev object since it is passed as an argument; the object has information about the event, notably the time at which the event occurred.

+ +

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:

+ +
var funcInit = function(){
+    // user code goes here and can safetly address all the HTML elements from the page
+    // since the document has successfully been 'loaded'
+}
+document.addEventListener('DOMContentLoaded', funcInit);
+
+ +

so that this code will only be executed after the document object emits the 'DOMContentLoaded' 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.

+ +

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.

+ +

Notable events

+ +

Web browsers define a large number of events so it is not practical to list them all. The Event Reference attempts to maintain a list of the standard Events used in modern web browsers.

+ +

In general, we can distinguish events of different kinds based on the object emitting the event including:

+ +
    +
  • the window object, such as due to resizing the browser,
  • +
  • the window.screen object, such as due to changes in device orientation,
  • +
  • the document object, including the loading, modification, user interaction, and unloading of the page,
  • +
  • the objects in the DOM (document object model) tree including user interactions or modifications,
  • +
  • the XMLHttpRequest objects used for network requests, and
  • +
  • the media objects such as audio and video, when the media stream players change state.
  • +
+ +

although this list is currently incomplete.

+ +

Some notable events are:

+ +
+

Note: This list of 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 this web page or in this Stack Overflow question.

+
+ +
    +
  • the global object window emits an event called 'load' 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,
  • +
  • the global object window emits an event called 'resize' when the height or the width of the browser window is changed by a user,
  • +
  • the DOM object document representing the HTML document emits an event called 'DOMContentLoaded' when the document has finished loading,
  • +
  • the DOM node objects such as div or button emit an event called 'click' when the user presses the mouse button while the mouse pointer is on top of the DOM node in the HTML page.
  • +
+ +

 

+ +

The Event object hierarchy

+ +

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 EventPrototype object.

+ +

A partial diagram of the class hierarchy of event objects is:

+ +
+

Note: This diagram is incomplete.

+
+ +

+ +

The Web API Documentation contains a page defining the Event object which also includes the known DOM event subclasses of the Event object.

+ +

Documents

+ +

Three sources on the MDN (Mozilla Developer Network) web site are particularly useful for programmers wanting to work with events:

+ + + +

 

+ +

 

+ +

 

diff --git a/files/ko/web/api/detecting_device_orientation/index.html b/files/ko/web/api/detecting_device_orientation/index.html deleted file mode 100644 index 995997b5ab..0000000000 --- a/files/ko/web/api/detecting_device_orientation/index.html +++ /dev/null @@ -1,274 +0,0 @@ ---- -title: 기기 방향 감지하기 -slug: Web/API/Detecting_device_orientation -translation_of: Web/API/Detecting_device_orientation -original_slug: WebAPI/Detecting_device_orientation ---- -
{{SeeCompatTable}}
- -

요약

- -

웹을 이용 가능한 기기들은 자신들의 방향을 알 수 있게 되었다. 즉, 중력과의 관계에서 자신의 방향의 변화를 나타내는 데이터를 알 수 있다는 뜻이다. 특히, 휴대 전화와 같이 손에 쥐고 쓸 수 있는 기기들은 이 정보를 화면을 수직으로 유지하기 위해 자동으로 회전시키는데 사용할 수 있고, 기기가 회전되어서 폭이 높이보다 길 때는 와이드 스크린으로 표시할 수 있게 된다.

- -

방향 정보를 다루는 두 가지 방법의 JavaScript 이벤트가 있다. 첫 번째는 {{domxref("DeviceOrientationEvent")}}로 가속도계가 기기의 방향의 변화를 감지했을 때 발생한다.  이 방향 이벤트들에 의해 보고되는 데이터를 받아서 처리함으로써, 사용자들이 기기를 움직이여서 생기는 방향과 높이의 변화를 상호 작용적으로 응답할 수 있게 된다.

- -

두 번째 이벤트는 {{domxref("DeviceMotionEvent")}}로 가속도에 변화가 일어났을 때 발생한다. 이 이벤트는 {{domxref("DeviceOrientationEvent")}}와는 방향이 아닌 가속도를 감지하고 있다는 점에서 다르다. 일반적으로{{domxref("DeviceMotionEvent")}}를 감지할 수 있는 센서들은 저장 장치들을 충격으로부터 보호하기 위해 노트북에서 사용되는 센서들을 포함한다. {{domxref("DeviceOrientationEvent")}}는 모바일 기기에서 주로 더 많이 나타난다.

- -

방향 이벤트 처리하기

- -

방향의 변화를 받기 위해 여러분이 해야하는 것은 {{ event("deviceorientation") }} 이벤트에 리스너를 등록하는 것 뿐이다:

- -
window.addEventListener("deviceorientation", handleOrientation, true);
-
- -

이벤트 리스너를 등록한 후에는 (여기에서는 JavaScript 함수 handleOrientation()), 리스너 함수가 업데이트 된 방향 데이터와 함께 주기적으로 호출된다.

- -

방향 이벤트는 다음 네 개의 값을 가진다:

- -
    -
  • {{ domxref("DeviceOrientationEvent.absolute") }}
  • -
  • {{ domxref("DeviceOrientationEvent.alpha") }}
  • -
  • {{ domxref("DeviceOrientationEvent.beta") }}
  • -
  • {{ domxref("DeviceOrientationEvent.gamma") }}
  • -
- -

이벤트 핸들러 함수는 보통 다음과 같다:

- -
function handleOrientation(event) {
-  var absolute = event.absolute;
-  var alpha    = event.alpha;
-  var beta     = event.beta;
-  var gamma    = event.gamma;
-
-  // Do stuff with the new orientation data
-}
-
- -

방향 값 설명

- -

각 축으로부터 보고된 값은 표준 좌표계 축을 중심으로 회전한 양을 가리킨다. 더 자세한 내용은 Orientation and motion data explained 문서에 나와있으며, 다음은 이를 간략하게 요약한 것이다.

- -
    -
  • {{ domxref("DeviceOrientationEvent.alpha") }} 값은 0도부터 360도까지 범위의 z축을 중심으로 한 기기의 움직임을 나타낸다.
  • -
  • {{ domxref("DeviceOrientationEvent.beta") }} 값은 -180도부터 180도까지 범위의 x축을 줌심으로 한 기기의 움직임을 나타낸다. 이는 기기의 앞뒤 움직임을 나타낸다.
  • -
  • {{ domxref("DeviceOrientationEvent.gamma") }} 값은 -90도부터 90도까지 범위의 y축을 중심으로 한 기기의 움직임을 나타낸다. 이는 기기의 좌우 움직임을 나타낸다.
  • -
- -

방향 예제

- -

이 예제는 {{event("deviceorientation")}} 이벤트를 지원하고 방향을 감지할 수 있는 기기에서 실행중인 모든 브라우저에서 작동한다.

- -

자 그럼, 정원에 공이 하나 있다고 상상해보자:

- -
<div class="garden">
-  <div class="ball"></div>
-</div>
-
-<pre class="output"></pre>
-
- -

이 정원은 가로 세로 200 픽셀이고(그렇다, 작은 정원이다), 정 중앙에 공이 있다:

- -
.garden {
-  position: relative;
-  width : 200px;
-  height: 200px;
-  border: 5px solid #CCC;
-  border-radius: 10px;
-}
-
-.ball {
-  position: absolute;
-  top   : 90px;
-  left  : 90px;
-  width : 20px;
-  height: 20px;
-  background: green;
-  border-radius: 100%;
-}
-
- -

이제, 우리가 기기를 움직이면 공도 따라서 움직일 것이다:

- -
var ball   = document.querySelector('.ball');
-var garden = document.querySelector('.garden');
-var output = document.querySelector('.output');
-
-var maxX = garden.clientWidth  - ball.clientWidth;
-var maxY = garden.clientHeight - ball.clientHeight;
-
-function handleOrientation(event) {
-  var x = event.beta;  // In degree in the range [-180,180]
-  var y = event.gamma; // In degree in the range [-90,90]
-
-  output.innerHTML  = "beta : " + x + "\n";
-  output.innerHTML += "gamma: " + y + "\n";
-
-  // Because we don't want to have the device upside down
-  // We constrain the x value to the range [-90,90]
-  if (x >  90) { x =  90};
-  if (x < -90) { x = -90};
-
-  // To make computation easier we shift the range of
-  // x and y to [0,180]
-  x += 90;
-  y += 90;
-
-  // 10 is half the size of the ball
-  // It center the positionning point to the center of the ball
-  ball.style.top  = (maxX*x/180 - 10) + "px";
-  ball.style.left = (maxY*y/180 - 10) + "px";
-}
-
-window.addEventListener('deviceorientation', handleOrientation);
-
- -

여기 실제로 실행해 볼 수 있는 예제이다:

- -
{{ EmbedLiveSample('Orientation_example', '230', '260') }}
- -
-

경고: Chrome과 Firefox는 동일한 방식으로 각을 다루지 않습니다. 그래서 어떤 축의 방향은 반대가 됩니다.

-
- -

모션 이벤트 처리하기

- -

모션 이벤트는 이벤트 이름이 {{ event("devicemotion") }}으로 다르다는 점을 제외하면, 방향 이벤트를 처리하는 방법과 동일하다.

- -
window.addEventListener("devicemotion", handleMotion, true);
- -

HandleMotion 함수의 파라미터로 넘겨진 {{ domxref("DeviceMotionEvent") }} 객체에 실제로 변화된 정보들이 담겨져 있다.

- -

모션 이벤트는 다음 네 가지 속성을 가진다:

- -
    -
  • {{ domxref("DeviceMotionEvent.acceleration") }}
  • -
  • {{ domxref("DeviceMotionEvent.accelerationIncludingGravity") }}
  • -
  • {{ domxref("DeviceMotionEvent.rotationRate") }}
  • -
  • {{ domxref("DeviceMotionEvent.interval") }}
  • -
- -

모션 값 설명

- -

{{ domxref("DeviceMotionEvent") }} 객체는 웹 개발자들에게 기기의 위치와 방향의 변화 속도에 관한 정보를 제공한다. 세 개의 축에 따라 변화한 정보가 제공된다 (자세한 내용은 Orientation and motion data explained 문서를 참조).

- -

{{domxref("DeviceMotionEvent.acceleration","acceleration")}}과 {{domxref("DeviceMotionEvent.accelerationIncludingGravity","accelerationIncludingGravity")}}에서, 각 축은 다음에 해당된다:

- -
    -
  • x: 서쪽에서 동쪽으로 나타나는 축을 의미한다
  • -
  • y: 남쪽에서 북쪽으로 나타나는 축을 의미한다
  • -
  • z: 땅에서 수직으로 나타나는 축을 의미한다
  • -
- -

{{domxref("DeviceMotionEvent.rotationRate","rotationRate")}}에서, 조금은 다르게, 각 값들은 다음에 해당된다:

- -
    -
  • alpha: 화면(또는 데스크탑의 키보드)에 수직인 축을 따른 회전율을 의미한다
  • -
  • beta: 화면(또는 데스크탑의 키보드)의 평면의 왼쪽에서 오른쪽으로 나타나는 축을 따른 회전율을 의미한다
  • -
  • gamma: 화면(또는 데스크탑의 키보드)의 평면의 아래에서 위쪽으로 나타나는 축을 따른 회전율을 의미한다
  • -
- -

마지막으로, {{domxref("DeviceMotionEvent.interval","interval")}}은 기기에서 데이터를 얻을 수 있는 시간 간격(단위는 밀리초)을 의미한다.

- -

스펙

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Device Orientation')}}{{Spec2('Device Orientation')}}Initial specification.
- -

브라우저 호환성

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
{{domxref("DeviceOrientationEvent")}}7.03.6[1]
- 6
{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
{{domxref("DeviceMotionEvent")}}{{ CompatVersionUnknown() }}6{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
{{domxref("DeviceOrientationEvent")}}3.03.6[1]
- 6
{{ CompatNo() }}{{ CompatNo() }}4.2
{{domxref("DeviceMotionEvent")}}{{ CompatVersionUnknown() }}6{{ CompatUnknown() }}{{ CompatUnknown() }}4.2
-
- -

Gecko 구현 참고 사항

- -
    -
  1. Firefox 3.6, 4, 5는 표준인 {{domxref("DeviceOrientationEvent")}} 이벤트가 아닌 mozOrientation 을 지원한다
  2. -
- -

참고 자료

- - diff --git a/files/ko/web/api/document_object_model/events/index.html b/files/ko/web/api/document_object_model/events/index.html deleted file mode 100644 index 2974c9d435..0000000000 --- a/files/ko/web/api/document_object_model/events/index.html +++ /dev/null @@ -1,84 +0,0 @@ ---- -title: Events and the DOM -slug: Web/API/Document_Object_Model/Events -translation_of: Web/API/Document_Object_Model/Events ---- -
{{DefaultAPISidebar("DOM")}}
- -

소개

- -

이 장에서는 DOM 이벤트 모델을 설명한다.  Event 인터페이스는 DOM의 노드에서 이벤트 등록 및  event listeners를 위한 인터페이스와 더불어 다양한 이벤트 인터페이스가 서로 어떻게 관련되는지 보여주는 몇 가지 더 긴 예와 함께 설명된다.

- -

There is an excellent diagram that clearly explains the three phases of event flow through the DOM in the DOM Level 3 Events draft.

- -

Also see Example 5: Event Propagation in the Examples chapter for a more detailed example of how events move through the DOM.

- -

Event listener등록

- -

DOM 요소에 대한 이벤트 핸들러를 등록하는 방법에는 3가지가 있다.

- -

{{domxref("EventTarget.addEventListener")}}

- -
// 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')
-}
-
- -

이 방식은 근대의 웹페이지에서 사용해야하는 방법이다.

- -
-

Note: Internet Explorer 6–8 didn't support this method, offering a similar {{domxref("EventTarget.attachEvent")}} API instead. For cross-browser compatibility, use one of the many JavaScript libraries available.

-
- -

더 자세한 내용은{{domxref("EventTarget.addEventListener")}}를 참조하세요.

- -

HTML 속성

- -
<button onclick="alert('Hello world!')">
-
- -

속성에서 JavaScript 코드는 이벤트 매개변수를 통해 이벤트 객체를 통과합니다. 반환 값은 HTML 사양에 설명된 특별한 방법으로 처리됩니다.

- -
-

경고: 이 방법은 피해야 합니다! 그것은 마크업을 부풀리고, 읽기 어렵게 만듭니다. 내용/구조와 행동에 대한 우려는 잘 분리되어 있지 않아 버그를 찾기가 더 어려워집니다.

-
- -

DOM 요소 특성

- -
// Assuming myButton is a button element
-myButton.onclick = function(event){alert('Hello world')}
-
- -

The function can be defined to take an event parameter. The return value is treated in a special way, described in the HTML specification.

- -

The problem with this method is that only one handler can be set per element and per event.

- -

Accessing Event interfaces

- -

Event handlers may be attached to various objects (including DOM elements, document, the {{domxref("window")}} object, etc.). When an event occurs, an event object is created and passed sequentially to the event listeners.

- -

The {{domxref("Event")}} interface is accessible from within the handler function, via the event object passed as the first argument. The following simple example shows how an event object is passed to the event handler function, and can be used from within one such function.

- -
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
-
- - - - diff --git a/files/ko/web/guide/events/index.html b/files/ko/web/guide/events/index.html deleted file mode 100644 index e952840d8e..0000000000 --- a/files/ko/web/guide/events/index.html +++ /dev/null @@ -1,51 +0,0 @@ ---- -title: Event developer guide -slug: Web/Guide/Events -tags: - - DOM - - Event - - Guide - - NeedsUpdate - - events -translation_of: Web/Guide/Events ---- -

{{draft()}}

- -

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.

- -

The overview page 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.

- -

The custom events page 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.

- -

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.

- -

The device 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 page on orientation coordinate systems and the page on the use of 3D transforms. That is different, but similar, to the change in device vertical orientation. 

- -

The window in which the browser is displayed which might trigger events, for example, change size if the user maximizes the window or otherwise changes it.

- -

The process 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.

- -

The user interaction 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:

- - - -

The modification of the web page in structure or content might trigger some events, as is explained in the mutation events page, but the use of these events has been deprecated in favour of the lighter Mutation Observer approach.

- -

The media streams embedded in the HTML documents might trigger some events, as explained in the media events page.

- -

The network requests made by a web page might trigger some events.

- -

There are many other sources of events defined by web browsers for which pages are not yet available in this guide.

- -
-

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.

-
- -

Docs

- -

{{LandingPageListSubpages}}

diff --git a/files/ko/web/guide/events/overview_of_events_and_handlers/index.html b/files/ko/web/guide/events/overview_of_events_and_handlers/index.html deleted file mode 100644 index c3f1a9205a..0000000000 --- a/files/ko/web/guide/events/overview_of_events_and_handlers/index.html +++ /dev/null @@ -1,142 +0,0 @@ ---- -title: Overview of Events and Handlers -slug: Web/Guide/Events/Overview_of_Events_and_Handlers -translation_of: Web/Guide/Events/Overview_of_Events_and_Handlers ---- -
-

 이 글은 이벤트 및 이벤트 핸들링(event handling)에 대한 개요로서, 웹 페이지가 열려있는 동안 일어나는 사건(incident)에 대해 반응할 수 있도록 하는 코드 설계 패턴에 대해 설명하고, 현 세대의 웹 브라우저에서 핸들링할 수 있는 사건의 종류에 대해 요약한다.

-
- -

 이벤트와 이벤트 핸들링은 웹 페이지가 사용자에 의해 열린 상태를 유지하는 동안 일어나는 사건에 대한 반응을 구현하기 위한 자바스크립트의 핵심적인 기술이다. 이러한 사건에는 페이지가 전시(display)되기 위한 준비과정 중 일어나는 사건, 웹 페이지상의 컨텐츠와 사용자의 상호작용에 의한 사건, 브라우저가 실행되는 기반 장치와 관련된 사건, 매체 스트림(media stream) 재생이나 애니메이션 시간 간격 등 기타 요인에 의한 사건 등이 있다.

- -

 이벤트와 이벤트 핸들링은 자바스크립트가 처음 도입된 시점부터 중심적인 역할을 했으며, 이와 함께 브라우저의 렌더링 아키텍처 역시 단일 처리경로(single pass) 페이지 렌더링으로부터 리플로우(reflow) 기반, 이벤트 구동식(driven) 페이지 렌더링 개념으로 바뀌었다.

- -

 최초에는 브라우저는 페이지의 모든 부분에 대한 문법분석(parse), 처리(process), 그리기(draw) 및 사용자에게 표현(present)까지의 모든 과정이 끝날 때까지 대기하고, 페이지 작업이 끝나면 그 상태로 바뀌지 않고 새 페이지 요청이 있어서 가져오기(fetch)작업이 일어나기 전까지는 그대로의 모습을 유지했다. 

- -

 리플로우 기반 이벤트 구동식 페이지 렌더링 개념으로 바뀐 뒤에는 브라우저는 처리, 그리기, 컨텐츠 표현(present), 반복순환작업을 다시 개시하도록 하는 이벤트 트리거에 대한 대기 등의 작업을 반복순환(loop)하여 수행한다. 이 이벤트 트리거라는 것은 이벤트를 발생하게 하는 사건을 이르는 것으로서, 네트워크상의 자원 로드 완료( 예 : 이미지가 다운로드되어 화면상에 그릴 수 있게 됨), 브라우저에 의한 자원의 문법분석 완료( 예 : HTML페이지 처리가 끝남) 페이지의 컨텐츠와 사용자와의 상호작용(예 : 버튼을 클릭한다) 등이 이러한 사건이 될 수 있다.

- -

 더글라스 크록포드는 An inconvenient API : The theory of the DOM(불편한 API : DOM의 이론)이라는 제목의 강연에서 이러한 변화를 여러 단원에 걸쳐 설명하였는데, 본래의 작업 흐름에서 이벤트 구동식 브라우저의 작업 흐름으로 바뀌는 것을 다음과 같이 보여주었다.

- -
A comparison of the sequential and event-driven browser load sequences.
- -

 두 번째 그림에 보이는 처리방식은 마지막 단계의 작업흐름을 변화시킴으로써 첫 번째 그림의 단일 경로 처리흐름에서 반복순환 흐름으로 바뀐 것을 보여준다. 두 번째 그림은 Paint작업이 끝나면 새로운 이벤트 발생에 대한 처리(이벤트 핸들링)를 하기 위해 이벤트를 기다리게 된다. 이 혁신적인 개념을 이용하면 자원을 다 획득하지 않았더라도 페이지를 부분적으로 렌더링하는 것이 가능하며, 최초에는 자바스크립트에 의해 발전된 이벤트 구동에 의한 동작 효과적으로 구현할 수 있다. (이 강의는 여기를 포함한 다양한 경로로 볼 수 있다) 현재 모든 자바스크립트 코드 실행 환경에서는 이벤트와 이벤트 핸들링을 사용한다.

- -

이벤트 설계 패턴

- -

이벤트 시스템은 근본적으로는 단순한 프로그래밍 설계 패턴이다. 이 패턴는 기본적으로 이벤트의 종류와 다음 사항에 대해 합의된 약속을 기반으로 한다.

- -
    -
  • 각 이벤트를 가리키는 이벤트명 문자열
  • -
  • 각 이벤트의 핵심 프로퍼티를 나타내기 위한 자료구조의 형식
  • -
  • 각 이벤트를 발동할 자바스크립트 객체
  • -
- -

패턴을 구현하기 위해서는 다음이 필요하다.

- -
    -
  • 위에서 약속된 자료구조를 인수로 받는 자바스크립트 함수를 정의한다.
  • -
  • 이벤트를 발동할 객체에 약속된 해당 이벤트의 이벤트명을 사용하여 위의 함수를 등록한다.
  • -
- -

이 함수는 리스너(listener) 또는 핸들러(handler)라는 혼용된 명칭으로 불린다. 이 패턴은 커스텀 이벤트에 관한 글에서 설명한 대로의 완전한 커스텀 이벤트를 사용하여 쉽게 구현할 수 있다. 이 패턴은 사용자 입력, 브라우저 활동 등에 의해 발동되는 다양한 이벤트를 정의하는 최신 웹 브라우저에서도 많이 사용한다.

- -

 최신 웹 브라우저는 이 이벤트 패턴을 표준화된 방식으로 구현한다. 브라우저는 어떤 이벤트의 프로퍼티를 나타내는 자료 구조로서  EventPrototype 객체를 원천으로 하는 어떤 객체를 사용한다. 또한 이러한 자료구조를 핸들링할 함수에 대한 등록 메소드로서 addEventListener 메소드를 사용하는데 이것은 인수로서 이벤트명과 핸들러 함수를 받는다. 마지막으로 브라우저는 이벤트 발동자(emitter)로 수많은 객체를 정의하며 또한 이 객체들에 의해 생성되는 여러 이벤트형(event type)을 정의한다.

- -

버튼 이벤트 핸들러 데모

- -

하나의 예시로서 브라우저 button 요소(element)는 'click'이라는 이름의 이벤트를 마우스 클릭 또는 터치스크린의 경우 손가락 터치에 반응하여 발동시킨다. 버튼은 HTML 페이지에서 다음과 같이 정의할 수 있다.

- -
<button id="buttonOne">Click here to emit a 'click' event</button>
- -

그리고 자바스크립트 코드에서 'click' 이벤트에 대한 리스너로서의 함수, 즉 핸들러로 사용할 함수를 정의한다.

- -
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 );
-};
- -

그 다음 해당 Button 객체와 함께 위의 함수를 등록하는데, 첫 번째 방법은 HTML 페이지의 DOM(문서 객체 모델) 표현법을 이용하여 다음과 같이 스크립트상에서 나타내는 방법이다. 

- -
var buttonDOMElement = document.querySelector('#buttonOne');
-buttonDOMElement.addEventListener('click', example_click_handler);
- -

또 다른 방법은 HTML 페이지 상에서 'onclick' 애트리뷰트의 값으로 핸들러로 쓸 함수를 대입시키는 것인데, 보통 이 방식은 매우 단순한 웹 페이지에서나 쓰인다.

- -

{{ EmbedLiveSample('Button_Event_Handler') }}

- -

This code relies on the agreement that there is a kind of event called 'click' which will call any listener (or 'handler') function with an Event object argument (actually, in this case a derivative MouseEvent object) and which will be fired by HTML button 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 buttonDOMElement Javascript object would call the example_click_handler function with an Event 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 ev object since it is passed as an argument; the object has information about the event, notably the time at which the event occurred.

- -

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:

- -
var funcInit = function(){
-    // user code goes here and can safetly address all the HTML elements from the page
-    // since the document has successfully been 'loaded'
-}
-document.addEventListener('DOMContentLoaded', funcInit);
-
- -

so that this code will only be executed after the document object emits the 'DOMContentLoaded' 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.

- -

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.

- -

Notable events

- -

Web browsers define a large number of events so it is not practical to list them all. The Event Reference attempts to maintain a list of the standard Events used in modern web browsers.

- -

In general, we can distinguish events of different kinds based on the object emitting the event including:

- -
    -
  • the window object, such as due to resizing the browser,
  • -
  • the window.screen object, such as due to changes in device orientation,
  • -
  • the document object, including the loading, modification, user interaction, and unloading of the page,
  • -
  • the objects in the DOM (document object model) tree including user interactions or modifications,
  • -
  • the XMLHttpRequest objects used for network requests, and
  • -
  • the media objects such as audio and video, when the media stream players change state.
  • -
- -

although this list is currently incomplete.

- -

Some notable events are:

- -
-

Note: This list of 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 this web page or in this Stack Overflow question.

-
- -
    -
  • the global object window emits an event called 'load' 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,
  • -
  • the global object window emits an event called 'resize' when the height or the width of the browser window is changed by a user,
  • -
  • the DOM object document representing the HTML document emits an event called 'DOMContentLoaded' when the document has finished loading,
  • -
  • the DOM node objects such as div or button emit an event called 'click' when the user presses the mouse button while the mouse pointer is on top of the DOM node in the HTML page.
  • -
- -

 

- -

The Event object hierarchy

- -

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 EventPrototype object.

- -

A partial diagram of the class hierarchy of event objects is:

- -
-

Note: This diagram is incomplete.

-
- -

- -

The Web API Documentation contains a page defining the Event object which also includes the known DOM event subclasses of the Event object.

- -

Documents

- -

Three sources on the MDN (Mozilla Developer Network) web site are particularly useful for programmers wanting to work with events:

- - - -

 

- -

 

- -

 

diff --git a/files/pt-br/_redirects.txt b/files/pt-br/_redirects.txt index ab7c16ba17..1ea76dec68 100644 --- a/files/pt-br/_redirects.txt +++ b/files/pt-br/_redirects.txt @@ -106,7 +106,7 @@ /pt-BR/docs/DOM/Document.querySelector /pt-BR/docs/Web/API/Document/querySelector /pt-BR/docs/DOM/Document.querySelectorAll /pt-BR/docs/Web/API/Document/querySelectorAll /pt-BR/docs/DOM/Referencia_do_DOM /pt-BR/docs/Web/API/Document_Object_Model -/pt-BR/docs/DOM/Referencia_do_DOM/Events /pt-BR/docs/Web/API/Document_Object_Model/Events +/pt-BR/docs/DOM/Referencia_do_DOM/Events /pt-BR/docs/orphaned/Web/API/Document_Object_Model/Events /pt-BR/docs/DOM/Referencia_do_DOM/Examples /pt-BR/docs/Web/API/Document_Object_Model/Examples /pt-BR/docs/DOM/Referencia_do_DOM/How_to_create_a_DOM_tree /pt-BR/docs/Web/API/Document_object_model/How_to_create_a_DOM_tree /pt-BR/docs/DOM/Referencia_do_DOM/Introdução /pt-BR/docs/Web/API/Document_Object_Model/Introduction @@ -561,6 +561,7 @@ /pt-BR/docs/Web/API/DocumentOrShadowRoot/activeElement /pt-BR/docs/Web/API/Document/activeElement /pt-BR/docs/Web/API/DocumentOrShadowRoot/elementFromPoint /pt-BR/docs/Web/API/Document/elementFromPoint /pt-BR/docs/Web/API/DocumentOrShadowRoot/getSelection /pt-BR/docs/Web/API/Document/getSelection +/pt-BR/docs/Web/API/Document_Object_Model/Events /pt-BR/docs/orphaned/Web/API/Document_Object_Model/Events /pt-BR/docs/Web/API/DocumentoXML /pt-BR/docs/Web/API/XMLDocument /pt-BR/docs/Web/API/Element.addEventListener /pt-BR/docs/Web/API/EventTarget/addEventListener /pt-BR/docs/Web/API/Element.getAttribute /pt-BR/docs/Web/API/Element/getAttribute @@ -730,8 +731,11 @@ /pt-BR/docs/Web/Guide/CSS/CSS_media_queries_(consultas_de_mídia_em_CSS) /pt-BR/docs/orphaned/Web/Guide/CSS/CSS_media_queries_(consultas_de_mídia_em_CSS) /pt-BR/docs/Web/Guide/CSS/Scaling_background_images /pt-BR/docs/Web/CSS/CSS_Backgrounds_and_Borders/Resizing_background_images /pt-BR/docs/Web/Guide/CSS/Understanding_z_index /pt-BR/docs/Web/CSS/CSS_Positioning/Understanding_z_index +/pt-BR/docs/Web/Guide/Events /pt-BR/docs/orphaned/Web/Guide/Events /pt-BR/docs/Web/Guide/Events/Creating_and_triggering_events /pt-BR/docs/orphaned/Web/Guide/Events/Creating_and_triggering_events +/pt-BR/docs/Web/Guide/Events/Event_handlers /pt-BR/docs/orphaned/Web/Guide/Events/Event_handlers /pt-BR/docs/Web/Guide/Events/Mutation_events /pt-BR/docs/orphaned/Web/Guide/Events/Mutation_events +/pt-BR/docs/Web/Guide/Events/Overview_of_Events_and_Handlers /pt-BR/docs/orphaned/Web/Guide/Events/Overview_of_Events_and_Handlers /pt-BR/docs/Web/Guide/Events/Touch_events /pt-BR/docs/Web/API/Touch_events /pt-BR/docs/Web/Guide/Events/criando_e_disparando_eventos /pt-BR/docs/orphaned/Web/Guide/Events/Creating_and_triggering_events /pt-BR/docs/Web/Guide/Gráficos /pt-BR/docs/Web/Guide/Graphics diff --git a/files/pt-br/_wikihistory.json b/files/pt-br/_wikihistory.json index a7076ab9f3..248512bfde 100644 --- a/files/pt-br/_wikihistory.json +++ b/files/pt-br/_wikihistory.json @@ -5813,24 +5813,6 @@ "Sheppy" ] }, - "Web/Guide/Events": { - "modified": "2019-03-23T23:21:12.584Z", - "contributors": [ - "Sheppy" - ] - }, - "Web/Guide/Events/Event_handlers": { - "modified": "2020-08-06T11:00:19.146Z", - "contributors": [ - "eziotristao" - ] - }, - "Web/Guide/Events/Overview_of_Events_and_Handlers": { - "modified": "2020-09-28T23:35:22.348Z", - "contributors": [ - "helton-mori-dev" - ] - }, "Web/Guide/Mobile": { "modified": "2020-04-05T18:24:36.523Z", "contributors": [ @@ -13208,12 +13190,6 @@ "meldenne" ] }, - "Web/API/Document_Object_Model/Events": { - "modified": "2020-08-30T22:44:17.906Z", - "contributors": [ - "bermarques" - ] - }, "Web/API/Document_Object_Model/Examples": { "modified": "2019-03-23T22:11:58.983Z", "contributors": [ @@ -17367,5 +17343,29 @@ "contributors": [ "JefersonOliveira90" ] + }, + "orphaned/Web/API/Document_Object_Model/Events": { + "modified": "2020-08-30T22:44:17.906Z", + "contributors": [ + "bermarques" + ] + }, + "orphaned/Web/Guide/Events/Event_handlers": { + "modified": "2020-08-06T11:00:19.146Z", + "contributors": [ + "eziotristao" + ] + }, + "orphaned/Web/Guide/Events": { + "modified": "2019-03-23T23:21:12.584Z", + "contributors": [ + "Sheppy" + ] + }, + "orphaned/Web/Guide/Events/Overview_of_Events_and_Handlers": { + "modified": "2020-09-28T23:35:22.348Z", + "contributors": [ + "helton-mori-dev" + ] } } \ No newline at end of file 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 +--- +
{{DefaultAPISidebar("DOM")}}
+ +

Introdução

+ +

Este capítulo descreve o Modelo de Eventos do DOM. A interface de Eventos é descrita, assim como a interface para registro de eventos em nodes(ou nódulos) no DOM, e event listeners, 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 DOM Level 3 Events draft.

+ +

Existe um excelente diagrama que explica claramente as três fases do percurso de eventos no DOM em DOM Level 3 Events draft.

+ +

Registrando event listeners

+ +

Existem 3 formas de registrar uma manipulação de eventos para um elemento DOM.

+ +

{{domxref("EventTarget.addEventListener")}}

+ +
// 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')
+}
+
+ +

Este é o método que você deve usar em páginas web modernas.

+ +
+

Nota: 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.

+
+ +

Mais detalhes podem encontrada na página de referência {{domxref("EventTarget.addEventListener")}}.

+ +

atributo HTML

+ +
<button onclick="alert('Hello world!')">
+
+ +

O código JavaScript no atributo é passado para o objeto Evento através do parâmetro event . O valor return é tratado de uma maneira especial, descrita na especificação HTML.

+ +
+

Cuidado: 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.

+
+ +

DOM element properties

+ +
// Supondo que myButton seja um elemento button
+myButton.onclick = function(event){alert('Hello world')}
+
+ +

A função pode ser definida para receber um parâmetro event . O valor return é tratado de maneira especial, descrita na especificação HTML.

+ +

O problema deste método é que apenas uma manipulação pode ser definida por elemento e por evento.

+ +

Acessando interfaces doEvento

+ +

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.

+ +

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.

+ +
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
+
+ + + + 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 +--- +

A plataforma web oferece várias maneiras de trabalhar com o DOM events. Duas abordagens comuns são: {{domxref("EventTarget.addEventListener", "addEventListener()")}} e o específico onevent que dispara um evento. Este artigo se concentra em como o último funciona.

+ +

Registering onevent handlers

+ +

The onevent 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 <body> element). Events are actions like:

+ +
    +
  • Being clicked
  • +
  • Detecting pressed keys
  • +
  • Getting focus
  • +
+ +

The on-event handler is usually named with the event it reacts to, like onclick, onkeypress, onfocus, etc.

+ +

You can specify an on<…> event handler for a particular event (such as {{event("click")}}) for a given object in different ways:

+ +
    +
  • Adding an HTML {{Glossary("attribute")}} named on<eventtype>:
    + <button onclick="handleClick()">,
  • +
  • Or by setting the corresponding {{Glossary("property/JavaScript", "property")}} from JavaScript:
    + document.querySelector("button").onclick = function(event) { … }.
  • +
+ +

An onevent 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.

+ +

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 myButton, you can do myButton.onclick(myEventObject) 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 onclick().

+ +

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.

+ +

Non-element objects

+ +

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 progress event on instances of XMLHttpRequest:

+ +
const xhr = new XMLHttpRequest();
+xhr.onprogress = function() { … };
+ +

HTML onevent attributes

+ +

HTML elements have attributes named onevent 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 onevent 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.

+ +

Further changes to the HTML attribute value can be done via the setAttribute method; Making changes to the JavaScript property will have no effect.

+ +

HTML

+ +

Given this HTML document:

+ +
<p>Demonstrating quirks of <code>on<em>event</em></code> HTML attributes on
+   <a onclick="log('Click!')">these three words</a>.
+</p>
+
+<div></div>
+ +

JavaScript

+ +

Then this JavaScript demonstrates that the value of the HTML attribute is unaffected by changes to the JavaScript object's property.

+ +
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>`);
+ +

Result

+ +

{{ EmbedLiveSample('HTML_onevent_attributes', '', '', '', 'Web/Guide/Events/Event_handlers') }}

+ +

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: onblur, onerror, onfocus, onload, and onscroll.)

+ +

Event handler's parameters, this binding, and the return value

+ +

When the event handler is specified as an HTML attribute, the specified code is wrapped into a function with the following parameters:

+ +
    +
  • event — for all event handlers except {{domxref("GlobalEventHandlers.onerror", "onerror")}}.
  • +
  • event, source, lineno, colno, and error for the {{domxref("GlobalEventHandlers.onerror", "onerror")}} event handler. Note that the event parameter actually contains the error message as a string.
  • +
+ +

When the event handler is invoked, the this keyword inside the handler is set to the DOM element on which the handler is registered. For more details, see the this keyword documentation.

+ +

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 "The event handler processing algorithm" in the HTML specification.

+ +

When the event handler is invoked

+ +
+

TBD (non-capturing listener)

+
+ +

Terminology

+ +

The term event handler may refer to:

+ +
    +
  • Any function or object that is registered to be notified of events
  • +
  • Or more specifically, to the mechanism of registering event listeners via on… attributes in HTML or properties in Web APIs, such as <button onclick="alert(this)"> or window.onload = function() { … }.
  • +
+ +

When discussing the various methods of listening to events:

+ +
    +
  • Event listener refers to a function or object registered via {{domxref("EventTarget.addEventListener()")}}
  • +
  • Event handler refers to a function registered via on… attributes or properties
  • +
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML5 W3C')}}
+ +

Browser compatibility

+ +

Detecting the presence of event handler properties

+ +

You can detect the presence of an event handler property with the JavaScript in operator. For example:

+ +
if ("onsomenewfeature" in window) {
+  /* do something amazing */
+}
+
+ +

Event handlers and prototypes

+ +

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 Window.prototype.onload. In the past, event handlers (onload, 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.

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 +--- +

{{draft()}}

+

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.

+

The overview page 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.

+

The custom events page 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.

+

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.

+

The device 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 page on orientation coordinate systems and the page on the use of 3D transforms. That is different, but similar, to the change in device vertical orientation. 

+

The window in which the browser is displayed which might trigger events, for example, change size if the user maximizes the window or otherwise changes it.

+

The process 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.

+

The user interaction 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:

+ +

The modification of the web page in structure or content might trigger some events, as is explained in the mutation events page, but the use of these events has been deprecated in favour of the lighter Mutation Observer approach.

+

The media streams embedded in the HTML documents might trigger some events, as explained in the media events page.

+

The network requests made by a web page might trigger some events.

+

There are many other sources of events defined by web browsers for which pages are not yet available in this guide.

+
+

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.

+
+

Docs

+

{{LandingPageListSubpages}}

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 +--- +
+

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.

+
+ +

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.

+ +

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, An Inconvenient API: The Theory of the DOM.

+ +

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 e.g., downloads an image that can now be drawn on the screen, the completion of parsing a resource by the browser e.g., processes the HTML content of a page, the interaction of a user with the contents of the page e.g., clicks a button. Douglas Crockford explains this change effectively in several lectures, notably his talk, An Inconvenient API: The Theory of the DOM, which shows the change in flow from the original browser flow

+ +
A comparison of the sequential and event-driven browser load sequences.
+ +

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 this one.) Currently, all execution environments for JavaScript code use events and event handling.

+ +

The event design pattern

+ +

The event system, at its core, is simply a programming design pattern. The pattern starts with an agreement over a kind of event and:

+ +
    +
  • the name String used for the event,
  • +
  • the type of the data structure used to represent the key properties of that event, and
  • +
  • the JavaScript object which will 'emit' that event.
  • +
+ +

The pattern is implemented by

+ +
    +
  • defining a JavaScript function which takes as an argument the data structure which was agreed upon, and
  • +
  • registering the function using the name String with the object which will emit the event.
  • +
+ +

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 article on custom events. The pattern is also used by modern web browsers which define many events emitted in response to user input or browser activity.

+ +

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 EventPrototype object. Browsers use as the registration method for the function which will handle those data structures a method called addEventListener 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.

+ +

Button Event Handler Demo

+ +

For example, browser button elements are intended to emit events named 'click' 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 button as:

+ +
<button id="buttonOne">Click here to emit a 'click' event</button>
+ +

and, in our JavaScript code, we could first define a function to listen to that 'click' event:

+ +
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 );
+};
+ +

and second register our function with the the Button object, either on the scripting side using the DOM (Document Object Model) representation of the HTML page:

+ +
var buttonDOMElement = document.querySelector('#buttonOne');
+buttonDOMElement.addEventListener('click', example_click_handler);
+ +

or within the HTML page by adding the function as the value of the 'onclick' attribute, although this second approach is usually only used in very simple web pages.

+ +

{{ EmbedLiveSample('Button_Event_Handler') }}

+ +

This code relies on the agreement that there is a kind of event called 'click' which will call any listener (or 'handler') function with an Event object argument (actually, in this case a derivative MouseEvent object) and which will be fired by HTML button 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 buttonDOMElement JavaScript object would call the example_click_handler function with an Event 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 ev object since it is passed as an argument; the object has information about the event, notably the time at which the event occurred.

+ +

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:

+ +
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);
+
+ +

so that this code will only be executed after the document object emits the 'DOMContentLoaded' 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.

+ +

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.

+ +

Notable events

+ +

Web browsers define a large number of events so it is not practical to list them all. The Event Reference attempts to maintain a list of the standard Events used in modern web browsers.

+ +

In general, we can distinguish events of different kinds based on the object emitting the event including:

+ +
    +
  • the window object, such as due to resizing the browser,
  • +
  • the window.screen object, such as due to changes in device orientation,
  • +
  • the document object, including the loading, modification, user interaction, and unloading of the page,
  • +
  • the objects in the DOM (document object model) tree including user interactions or modifications,
  • +
  • the XMLHttpRequest objects used for network requests, and
  • +
  • the media objects such as audio and video, when the media stream players change state.
  • +
+ +

although this list is currently incomplete.

+ +

Some notable events are:

+ +
+

Note: 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 this web page or in this Stack Overflow question.

+
+ +
    +
  • the global object window emits an event called 'load' 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,
  • +
  • the global object window emits an event called 'resize' when the height or the width of the browser window is changed by a user,
  • +
  • the DOM object document representing the HTML document emits an event called 'DOMContentLoaded' when the document has finished loading,
  • +
  • the DOM node objects such as div or button emit an event called 'click' when the user presses the mouse button while the mouse pointer is on top of the DOM node in the HTML page.
  • +
+ + + +

The Event object hierarchy

+ +

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 EventPrototype object.

+ +

A partial diagram of the class hierarchy of event objects is:

+ +
+

Note: This diagram is incomplete.

+
+ +

+ +

The Web API Documentation contains a page defining the Event object which also includes the known DOM event subclasses of the Event object.

+ +

Documents

+ +

Three sources on the MDN (Mozilla Developer Network) web site are particularly useful for programmers wanting to work with events:

+ + diff --git a/files/pt-br/web/api/document_object_model/events/index.html b/files/pt-br/web/api/document_object_model/events/index.html deleted file mode 100644 index cd82ef8b39..0000000000 --- a/files/pt-br/web/api/document_object_model/events/index.html +++ /dev/null @@ -1,83 +0,0 @@ ---- -title: Events and the DOM -slug: Web/API/Document_Object_Model/Events -translation_of: Web/API/Document_Object_Model/Events -original_slug: DOM/Referencia_do_DOM/Events ---- -
{{DefaultAPISidebar("DOM")}}
- -

Introdução

- -

Este capítulo descreve o Modelo de Eventos do DOM. A interface de Eventos é descrita, assim como a interface para registro de eventos em nodes(ou nódulos) no DOM, e event listeners, 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 DOM Level 3 Events draft.

- -

Existe um excelente diagrama que explica claramente as três fases do percurso de eventos no DOM em DOM Level 3 Events draft.

- -

Registrando event listeners

- -

Existem 3 formas de registrar uma manipulação de eventos para um elemento DOM.

- -

{{domxref("EventTarget.addEventListener")}}

- -
// 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')
-}
-
- -

Este é o método que você deve usar em páginas web modernas.

- -
-

Nota: 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.

-
- -

Mais detalhes podem encontrada na página de referência {{domxref("EventTarget.addEventListener")}}.

- -

atributo HTML

- -
<button onclick="alert('Hello world!')">
-
- -

O código JavaScript no atributo é passado para o objeto Evento através do parâmetro event . O valor return é tratado de uma maneira especial, descrita na especificação HTML.

- -
-

Cuidado: 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.

-
- -

DOM element properties

- -
// Supondo que myButton seja um elemento button
-myButton.onclick = function(event){alert('Hello world')}
-
- -

A função pode ser definida para receber um parâmetro event . O valor return é tratado de maneira especial, descrita na especificação HTML.

- -

O problema deste método é que apenas uma manipulação pode ser definida por elemento e por evento.

- -

Acessando interfaces doEvento

- -

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.

- -

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.

- -
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
-
- - - - diff --git a/files/pt-br/web/guide/events/event_handlers/index.html b/files/pt-br/web/guide/events/event_handlers/index.html deleted file mode 100644 index f558992d27..0000000000 --- a/files/pt-br/web/guide/events/event_handlers/index.html +++ /dev/null @@ -1,164 +0,0 @@ ---- -title: DOM onevent handlers -slug: Web/Guide/Events/Event_handlers -translation_of: Web/Guide/Events/Event_handlers ---- -

A plataforma web oferece várias maneiras de trabalhar com o DOM events. Duas abordagens comuns são: {{domxref("EventTarget.addEventListener", "addEventListener()")}} e o específico onevent que dispara um evento. Este artigo se concentra em como o último funciona.

- -

Registering onevent handlers

- -

The onevent 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 <body> element). Events are actions like:

- -
    -
  • Being clicked
  • -
  • Detecting pressed keys
  • -
  • Getting focus
  • -
- -

The on-event handler is usually named with the event it reacts to, like onclick, onkeypress, onfocus, etc.

- -

You can specify an on<…> event handler for a particular event (such as {{event("click")}}) for a given object in different ways:

- -
    -
  • Adding an HTML {{Glossary("attribute")}} named on<eventtype>:
    - <button onclick="handleClick()">,
  • -
  • Or by setting the corresponding {{Glossary("property/JavaScript", "property")}} from JavaScript:
    - document.querySelector("button").onclick = function(event) { … }.
  • -
- -

An onevent 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.

- -

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 myButton, you can do myButton.onclick(myEventObject) 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 onclick().

- -

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.

- -

Non-element objects

- -

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 progress event on instances of XMLHttpRequest:

- -
const xhr = new XMLHttpRequest();
-xhr.onprogress = function() { … };
- -

HTML onevent attributes

- -

HTML elements have attributes named onevent 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 onevent 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.

- -

Further changes to the HTML attribute value can be done via the setAttribute method; Making changes to the JavaScript property will have no effect.

- -

HTML

- -

Given this HTML document:

- -
<p>Demonstrating quirks of <code>on<em>event</em></code> HTML attributes on
-   <a onclick="log('Click!')">these three words</a>.
-</p>
-
-<div></div>
- -

JavaScript

- -

Then this JavaScript demonstrates that the value of the HTML attribute is unaffected by changes to the JavaScript object's property.

- -
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>`);
- -

Result

- -

{{ EmbedLiveSample('HTML_onevent_attributes', '', '', '', 'Web/Guide/Events/Event_handlers') }}

- -

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: onblur, onerror, onfocus, onload, and onscroll.)

- -

Event handler's parameters, this binding, and the return value

- -

When the event handler is specified as an HTML attribute, the specified code is wrapped into a function with the following parameters:

- -
    -
  • event — for all event handlers except {{domxref("GlobalEventHandlers.onerror", "onerror")}}.
  • -
  • event, source, lineno, colno, and error for the {{domxref("GlobalEventHandlers.onerror", "onerror")}} event handler. Note that the event parameter actually contains the error message as a string.
  • -
- -

When the event handler is invoked, the this keyword inside the handler is set to the DOM element on which the handler is registered. For more details, see the this keyword documentation.

- -

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 "The event handler processing algorithm" in the HTML specification.

- -

When the event handler is invoked

- -
-

TBD (non-capturing listener)

-
- -

Terminology

- -

The term event handler may refer to:

- -
    -
  • Any function or object that is registered to be notified of events
  • -
  • Or more specifically, to the mechanism of registering event listeners via on… attributes in HTML or properties in Web APIs, such as <button onclick="alert(this)"> or window.onload = function() { … }.
  • -
- -

When discussing the various methods of listening to events:

- -
    -
  • Event listener refers to a function or object registered via {{domxref("EventTarget.addEventListener()")}}
  • -
  • Event handler refers to a function registered via on… attributes or properties
  • -
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML5 W3C')}}
- -

Browser compatibility

- -

Detecting the presence of event handler properties

- -

You can detect the presence of an event handler property with the JavaScript in operator. For example:

- -
if ("onsomenewfeature" in window) {
-  /* do something amazing */
-}
-
- -

Event handlers and prototypes

- -

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 Window.prototype.onload. In the past, event handlers (onload, 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.

diff --git a/files/pt-br/web/guide/events/index.html b/files/pt-br/web/guide/events/index.html deleted file mode 100644 index 65b5775a16..0000000000 --- a/files/pt-br/web/guide/events/index.html +++ /dev/null @@ -1,36 +0,0 @@ ---- -title: Event developer guide -slug: Web/Guide/Events -tags: - - DOM - - Event - - Guide - - NeedsTranslation - - TopicStub - - events -translation_of: Web/Guide/Events ---- -

{{draft()}}

-

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.

-

The overview page 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.

-

The custom events page 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.

-

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.

-

The device 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 page on orientation coordinate systems and the page on the use of 3D transforms. That is different, but similar, to the change in device vertical orientation. 

-

The window in which the browser is displayed which might trigger events, for example, change size if the user maximizes the window or otherwise changes it.

-

The process 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.

-

The user interaction 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:

- -

The modification of the web page in structure or content might trigger some events, as is explained in the mutation events page, but the use of these events has been deprecated in favour of the lighter Mutation Observer approach.

-

The media streams embedded in the HTML documents might trigger some events, as explained in the media events page.

-

The network requests made by a web page might trigger some events.

-

There are many other sources of events defined by web browsers for which pages are not yet available in this guide.

-
-

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.

-
-

Docs

-

{{LandingPageListSubpages}}

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 deleted file mode 100644 index 2593d5641e..0000000000 --- a/files/pt-br/web/guide/events/overview_of_events_and_handlers/index.html +++ /dev/null @@ -1,132 +0,0 @@ ---- -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 ---- -
-

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.

-
- -

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.

- -

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, An Inconvenient API: The Theory of the DOM.

- -

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 e.g., downloads an image that can now be drawn on the screen, the completion of parsing a resource by the browser e.g., processes the HTML content of a page, the interaction of a user with the contents of the page e.g., clicks a button. Douglas Crockford explains this change effectively in several lectures, notably his talk, An Inconvenient API: The Theory of the DOM, which shows the change in flow from the original browser flow

- -
A comparison of the sequential and event-driven browser load sequences.
- -

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 this one.) Currently, all execution environments for JavaScript code use events and event handling.

- -

The event design pattern

- -

The event system, at its core, is simply a programming design pattern. The pattern starts with an agreement over a kind of event and:

- -
    -
  • the name String used for the event,
  • -
  • the type of the data structure used to represent the key properties of that event, and
  • -
  • the JavaScript object which will 'emit' that event.
  • -
- -

The pattern is implemented by

- -
    -
  • defining a JavaScript function which takes as an argument the data structure which was agreed upon, and
  • -
  • registering the function using the name String with the object which will emit the event.
  • -
- -

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 article on custom events. The pattern is also used by modern web browsers which define many events emitted in response to user input or browser activity.

- -

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 EventPrototype object. Browsers use as the registration method for the function which will handle those data structures a method called addEventListener 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.

- -

Button Event Handler Demo

- -

For example, browser button elements are intended to emit events named 'click' 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 button as:

- -
<button id="buttonOne">Click here to emit a 'click' event</button>
- -

and, in our JavaScript code, we could first define a function to listen to that 'click' event:

- -
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 );
-};
- -

and second register our function with the the Button object, either on the scripting side using the DOM (Document Object Model) representation of the HTML page:

- -
var buttonDOMElement = document.querySelector('#buttonOne');
-buttonDOMElement.addEventListener('click', example_click_handler);
- -

or within the HTML page by adding the function as the value of the 'onclick' attribute, although this second approach is usually only used in very simple web pages.

- -

{{ EmbedLiveSample('Button_Event_Handler') }}

- -

This code relies on the agreement that there is a kind of event called 'click' which will call any listener (or 'handler') function with an Event object argument (actually, in this case a derivative MouseEvent object) and which will be fired by HTML button 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 buttonDOMElement JavaScript object would call the example_click_handler function with an Event 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 ev object since it is passed as an argument; the object has information about the event, notably the time at which the event occurred.

- -

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:

- -
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);
-
- -

so that this code will only be executed after the document object emits the 'DOMContentLoaded' 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.

- -

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.

- -

Notable events

- -

Web browsers define a large number of events so it is not practical to list them all. The Event Reference attempts to maintain a list of the standard Events used in modern web browsers.

- -

In general, we can distinguish events of different kinds based on the object emitting the event including:

- -
    -
  • the window object, such as due to resizing the browser,
  • -
  • the window.screen object, such as due to changes in device orientation,
  • -
  • the document object, including the loading, modification, user interaction, and unloading of the page,
  • -
  • the objects in the DOM (document object model) tree including user interactions or modifications,
  • -
  • the XMLHttpRequest objects used for network requests, and
  • -
  • the media objects such as audio and video, when the media stream players change state.
  • -
- -

although this list is currently incomplete.

- -

Some notable events are:

- -
-

Note: 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 this web page or in this Stack Overflow question.

-
- -
    -
  • the global object window emits an event called 'load' 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,
  • -
  • the global object window emits an event called 'resize' when the height or the width of the browser window is changed by a user,
  • -
  • the DOM object document representing the HTML document emits an event called 'DOMContentLoaded' when the document has finished loading,
  • -
  • the DOM node objects such as div or button emit an event called 'click' when the user presses the mouse button while the mouse pointer is on top of the DOM node in the HTML page.
  • -
- - - -

The Event object hierarchy

- -

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 EventPrototype object.

- -

A partial diagram of the class hierarchy of event objects is:

- -
-

Note: This diagram is incomplete.

-
- -

- -

The Web API Documentation contains a page defining the Event object which also includes the known DOM event subclasses of the Event object.

- -

Documents

- -

Three sources on the MDN (Mozilla Developer Network) web site are particularly useful for programmers wanting to work with events:

- - diff --git a/files/pt-pt/_redirects.txt b/files/pt-pt/_redirects.txt index 5ae20c7836..60efdb4607 100644 --- a/files/pt-pt/_redirects.txt +++ b/files/pt-pt/_redirects.txt @@ -933,7 +933,8 @@ /pt-PT/docs/Web/Guide/AJAX/Como_começar /pt-PT/docs/Web/Guide/AJAX/Getting_Started /pt-PT/docs/Web/Guide/AJAX/Comunidade /pt-PT/docs/Web/Guide/AJAX/Community /pt-PT/docs/Web/Guide/CSS /pt-PT/docs/Learn/CSS -/pt-PT/docs/Web/Guide/Eventos /pt-PT/docs/Web/Guide/Events +/pt-PT/docs/Web/Guide/Eventos /pt-PT/docs/orphaned/Web/Guide/Events +/pt-PT/docs/Web/Guide/Events /pt-PT/docs/orphaned/Web/Guide/Events /pt-PT/docs/Web/Guide/Gráficos /pt-PT/docs/Web/Guide/Graphics /pt-PT/docs/Web/Guide/HTML /pt-PT/docs/Learn/HTML /pt-PT/docs/Web/Guide/HTML/Categorias_de_conteudo /pt-PT/docs/Web/Guide/HTML/Content_categories diff --git a/files/pt-pt/_wikihistory.json b/files/pt-pt/_wikihistory.json index 93134770ca..fdb997ca71 100644 --- a/files/pt-pt/_wikihistory.json +++ b/files/pt-pt/_wikihistory.json @@ -4423,12 +4423,6 @@ "Anonymous" ] }, - "Web/Guide/Events": { - "modified": "2019-03-23T22:01:48.833Z", - "contributors": [ - "Anonymous" - ] - }, "Web/Guide/Graphics": { "modified": "2019-03-18T21:46:51.581Z", "contributors": [ @@ -5188,5 +5182,11 @@ "contributors": [ "joaonunomota" ] + }, + "orphaned/Web/Guide/Events": { + "modified": "2019-03-23T22:01:48.833Z", + "contributors": [ + "Anonymous" + ] } } \ No newline at end of file diff --git a/files/pt-pt/orphaned/web/guide/events/index.html b/files/pt-pt/orphaned/web/guide/events/index.html new file mode 100644 index 0000000000..f8f218d1c1 --- /dev/null +++ b/files/pt-pt/orphaned/web/guide/events/index.html @@ -0,0 +1,134 @@ +--- +title: Guia do programador de eventos +slug: orphaned/Web/Guide/Events +tags: + - DOM + - Evento + - Guía + - Precisa de Atualização +translation_of: Web/Guide/Events +original_slug: Web/Guide/Events +--- +

{{draft()}}

+ +

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.

+ +

The overview page 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.

+ +

The custom events page 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.

+ +

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.

+ +

The device 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 page on orientation coordinate systems and the page on the use of 3D transforms. That is different, but similar, to the change in device vertical orientation. 

+ +

The window in which the browser is displayed can trigger events; for example, change size if the user maximizes the window or otherwise changes it.

+ +

The process loading of a web page can 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.

+ +

The user interaction with the web page contents can 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:

+ + + +

The modification of the web page in structure or content might trigger some events, as explained in the mutation events page, but the use of these events has been deprecated in favour of the lighter Mutation Observer approach.

+ +

The media streams embedded in the HTML documents might trigger some events, as explained in the media events page.

+ +

The network requests made by a web page might trigger some events.

+ +

There are many other sources of events defined by web browsers for which pages are not yet available in this guide.

+ +
+

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.

+
+ +

Documentos

+ +

{{LandingPageListSubpages}}

+ +
+ + + + + +
diff --git a/files/pt-pt/web/guide/events/index.html b/files/pt-pt/web/guide/events/index.html deleted file mode 100644 index 88b9c2f2c8..0000000000 --- a/files/pt-pt/web/guide/events/index.html +++ /dev/null @@ -1,134 +0,0 @@ ---- -title: Guia do programador de eventos -slug: Web/Guide/Events -tags: - - DOM - - Evento - - Guía - - Precisa de Atualização -translation_of: Web/Guide/Events -original_slug: Web/Guide/Eventos ---- -

{{draft()}}

- -

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.

- -

The overview page 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.

- -

The custom events page 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.

- -

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.

- -

The device 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 page on orientation coordinate systems and the page on the use of 3D transforms. That is different, but similar, to the change in device vertical orientation. 

- -

The window in which the browser is displayed can trigger events; for example, change size if the user maximizes the window or otherwise changes it.

- -

The process loading of a web page can 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.

- -

The user interaction with the web page contents can 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:

- - - -

The modification of the web page in structure or content might trigger some events, as explained in the mutation events page, but the use of these events has been deprecated in favour of the lighter Mutation Observer approach.

- -

The media streams embedded in the HTML documents might trigger some events, as explained in the media events page.

- -

The network requests made by a web page might trigger some events.

- -

There are many other sources of events defined by web browsers for which pages are not yet available in this guide.

- -
-

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.

-
- -

Documentos

- -

{{LandingPageListSubpages}}

- -
- - - - - -
diff --git a/files/ru/_redirects.txt b/files/ru/_redirects.txt index 2e9994307f..f1cbdfc056 100644 --- a/files/ru/_redirects.txt +++ b/files/ru/_redirects.txt @@ -47,7 +47,7 @@ /ru/docs/Creating_Custom_Firefox_Extensions_with_the_Mozilla_Build_System /ru/docs/orphaned/Создание_расширения_для_Firefox_с_использованием_Mozilla_Build_System /ru/docs/DOM /ru/docs/conflicting/Web/API/Document_Object_Model /ru/docs/DOM/DOM_Reference /ru/docs/Web/API/Document_Object_Model -/ru/docs/DOM/DOM_Reference/Events /ru/docs/Web/API/Document_Object_Model/Events +/ru/docs/DOM/DOM_Reference/Events /ru/docs/orphaned/Web/API/Document_Object_Model/Events /ru/docs/DOM/DOM_Reference/Examples /ru/docs/Web/API/Document_Object_Model/Examples /ru/docs/DOM/DOM_Reference/Locating_DOM_elements_using_selectors /ru/docs/Web/API/Document_object_model/Locating_DOM_elements_using_selectors /ru/docs/DOM/DOM_Reference/Введение /ru/docs/Web/API/Document_Object_Model/Introduction @@ -405,6 +405,7 @@ /ru/docs/Web/API/Document/domConfig /ru/docs/Web/API/Document /ru/docs/Web/API/DocumentOrShadowRoot/activeElement /ru/docs/Web/API/Document/activeElement /ru/docs/Web/API/DocumentOrShadowRoot/getSelection /ru/docs/Web/API/Document/getSelection +/ru/docs/Web/API/Document_Object_Model/Events /ru/docs/orphaned/Web/API/Document_Object_Model/Events /ru/docs/Web/API/Element.getBoundingClientRect /ru/docs/Web/API/Element/getBoundingClientRect /ru/docs/Web/API/Element.insertAdjacentHTML /ru/docs/Web/API/Element/insertAdjacentHTML /ru/docs/Web/API/Element/accessKey /ru/docs/Web/API/HTMLElement/accessKey @@ -600,8 +601,11 @@ /ru/docs/Web/Guide/CSS/Using_multi-column_layouts /ru/docs/Web/CSS/CSS_Columns/Using_multi-column_layouts /ru/docs/Web/Guide/CSS/Visual_formatting_model /ru/docs/Web/CSS/Visual_formatting_model /ru/docs/Web/Guide/CSS/ispolzovanie_css_animatciy /ru/docs/Web/CSS/CSS_Animations/Using_CSS_animations +/ru/docs/Web/Guide/Events /ru/docs/orphaned/Web/Guide/Events /ru/docs/Web/Guide/Events/Creating_and_triggering_events /ru/docs/orphaned/Web/Guide/Events/Creating_and_triggering_events +/ru/docs/Web/Guide/Events/Event_handlers /ru/docs/orphaned/Web/Guide/Events/Event_handlers /ru/docs/Web/Guide/Events/Media_events /ru/docs/orphaned/Web/Guide/Events/Media_events +/ru/docs/Web/Guide/Events/Overview_of_Events_and_Handlers /ru/docs/orphaned/Web/Guide/Events/Overview_of_Events_and_Handlers /ru/docs/Web/Guide/Events/Создание_и_вызов_событий /ru/docs/orphaned/Web/Guide/Events/Creating_and_triggering_events /ru/docs/Web/Guide/HTML /ru/docs/Learn/HTML /ru/docs/Web/Guide/HTML/Canvas_tutorial /ru/docs/Web/API/Canvas_API/Tutorial diff --git a/files/ru/_wikihistory.json b/files/ru/_wikihistory.json index a2df374b41..613d1d702f 100644 --- a/files/ru/_wikihistory.json +++ b/files/ru/_wikihistory.json @@ -11546,29 +11546,6 @@ "akhabibullina" ] }, - "Web/Guide/Events": { - "modified": "2020-08-20T10:40:53.452Z", - "contributors": [ - "bogpok", - "Llorephie", - "Tihoem", - "Jeremie" - ] - }, - "Web/Guide/Events/Event_handlers": { - "modified": "2020-03-26T12:45:30.049Z", - "contributors": [ - "ellizii" - ] - }, - "Web/Guide/Events/Overview_of_Events_and_Handlers": { - "modified": "2019-06-24T11:18:00.027Z", - "contributors": [ - "kvandreev", - "MuradAz", - "curdwithraisins" - ] - }, "Web/Guide/HTML/Content_categories": { "modified": "2019-09-23T08:37:02.214Z", "contributors": [ @@ -19836,12 +19813,6 @@ "RAP1D" ] }, - "Web/API/Document_Object_Model/Events": { - "modified": "2019-03-18T21:18:44.250Z", - "contributors": [ - "SphinxKnight" - ] - }, "Web/API/Document_Object_Model/Examples": { "modified": "2019-09-25T18:36:16.946Z", "contributors": [ @@ -25988,5 +25959,34 @@ "lazyexpert", "YuryT" ] + }, + "orphaned/Web/API/Document_Object_Model/Events": { + "modified": "2019-03-18T21:18:44.250Z", + "contributors": [ + "SphinxKnight" + ] + }, + "orphaned/Web/Guide/Events/Event_handlers": { + "modified": "2020-03-26T12:45:30.049Z", + "contributors": [ + "ellizii" + ] + }, + "orphaned/Web/Guide/Events": { + "modified": "2020-08-20T10:40:53.452Z", + "contributors": [ + "bogpok", + "Llorephie", + "Tihoem", + "Jeremie" + ] + }, + "orphaned/Web/Guide/Events/Overview_of_Events_and_Handlers": { + "modified": "2019-06-24T11:18:00.027Z", + "contributors": [ + "kvandreev", + "MuradAz", + "curdwithraisins" + ] } } \ No newline at end of file diff --git a/files/ru/orphaned/web/api/document_object_model/events/index.html b/files/ru/orphaned/web/api/document_object_model/events/index.html new file mode 100644 index 0000000000..3bdc87fe96 --- /dev/null +++ b/files/ru/orphaned/web/api/document_object_model/events/index.html @@ -0,0 +1,81 @@ +--- +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 +--- +

Вступление

+ +

Вступление

+ +

В этой главе описывается модель событий DOM. Топ скрыть Интерфейс сам по себе описано, а также интерфейсы для регистрации событий на узлах в DOM, Также а обработчики события Главного , Также а Несколько больше Примеры, которые показывают, как Различные интерфейсы связаны друг события Главного с другом.

+ +

Существует отличная диаграмма, которая чётко объясняет события трёх этапов через DOM в проекте DOM Level 3 Events .

+ +

Также см. Пример 5: Распространение событий в главе «Примеры» для более подробного примера.

+ +

Регистрация обработчиков событий

+ +

Есть 3 способа регистрации обработанных событий для элемента DOM.

+ +

EventTarget.addEventListener

+ +
// Предполагая, что myButton является элементом кнопки
+myButton.addEventListener ('click', greet, false);
+function greet (event) {
+    // распечатать и посмотреть на объект события
+    // всегда печатать аргументы в случае пропуска любых других аргументов
+    console.log ('greet:', arguments);
+    оповещение («Привет, мир»);
+}
+
+ +

Это метод, который вы должны использовать на современных веб-страницах.

+ +

Примечание. Internet Explorer 6-8 не поддерживает этот метод, предлагая аналогичный {{domxref ("EventTarget.attachEvent")}} API. Для кросс-браузерной совместимости используйте одну из множества доступных библиотек JavaScript.

+ +

Дополнительную информацию можно найти на справочной странице {{domxref ("EventTarget.addEventListener")}}.

+ +

Атрибут HTML

+ +
<button onclick = "alert ('Hello world!')">
+
+ +

Код JavaScript в атрибуте передаётся объекту Event через eventпараметр. Возвращаемое значение обрабатывается особым образом, описанным в спецификации HTML .

+ +

Этого пути следует избегать. Это делает разметку больше и менее читаемой. Проблемы содержания / структуры и поведения плохо разделены, что затрудняет поиск ошибки.

+ +

Свойства элемента DOM

+ +
// Предполагая, что myButton является элементом кнопки
+myButton.onclick = function(event){alert('Hello world');};
+
+ +

Функция может быть определена для получения eventпараметра. Возвращаемое значение обрабатывается особым образом, описанным в спецификации HTML .

+ +

Проблема этого метода в том, что для каждого элемента и для каждого события может быть установлен только один обработчик.

+ +

Доступ к интерфейсам событий

+ +

Обработчики событий могут быть присоединены к различным объектам, включая элементы DOM, документ, объект окна и т. Д. Когда происходит событие, объект события создаётся и последовательно передаётся обработчикам события.

+ +

Интерфейс {{domxref ("Event")}} доступен из функции-обработчика через объект события, переданный в качестве первого аргумента. В следующем простом примере показано, как объект события передаётся в функцию-обработчик события и может использоваться из одной такой функции.

+ +
function print(evt) {
+  // параметру evt автоматически назначается объект события
+  // позаботимся о различиях в console.log и alert
+  console.log('print:', evt);
+  alert(evt);
+}
+// любая функция должна иметь подходящее имя, это то, что называется семантическим
+table_el.onclick = print; 
+
+ + + + diff --git a/files/ru/orphaned/web/guide/events/event_handlers/index.html b/files/ru/orphaned/web/guide/events/event_handlers/index.html new file mode 100644 index 0000000000..c30df7b474 --- /dev/null +++ b/files/ru/orphaned/web/guide/events/event_handlers/index.html @@ -0,0 +1,167 @@ +--- +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 +--- +

Веб-платформа предоставляет несколько способов получения уведомлений о событиях DOM. Два общих подхода - это {{domxref ("EventTarget.addEventListener", " addEventListener ()")}} и конкретные обработчики onevent . Эта страница посвящена тому, как работают последние.

+ +

Регистрация обработчиков onevent

+ +

Обработчики onevent - это свойства определённых элементов DOM, позволяющие управлять тем, как этот элемент реагирует на события. Элементы могут быть интерактивными (ссылки, кнопки, изображения, формы и т. д.) или неинтерактивными (например, элемент base <body>). События - это такие действия, как:

+ +
    +
  • Клик мышкой
  • +
  • Нажатие клавиш
  • +
  • Получение фокуса
  • +
+ +

Обработчик on-event обычно называется с именем события, на которое он реагирует, например onclick , onkeypress , onfocus и т. д.

+ +

Вы можете указать обработчик событий on<...> для конкретного события (например, {{event("click")}}) для данного объекта различными способами:

+ +
    +
  • Добавление HTML элемента {{Glossary("attribute")}} с событием on<eventtype>:
    + <button onclick="handleClick()">,
  • +
  • Или установив соответствующий параметр {{Glossary("property/JavaScript", "property")}} из JavaScript:
    + document.querySelector("button").onclick = function(event) { … }.
  • +
+ +

Свойство обработчика событий onevent  служит своего рода заполнителем, которому может быть назначен один обработчик событий. Чтобы разрешить установку нескольких обработчиков для одного и того же события на данном объекте, вы можете вызвать метод {{domxref("EventTarget.addEventListener", " addEventListener ()")}} , который управляет списком обработчиков для данного события на объекте. Затем обработчик можно удалить из объекта, вызвав его функцию {{domxref ("EventTarget.removeEventListener", "removeEventListener()")}} .

+ +

Когда происходит событие, которое применяется к элементу, каждый из его обработчиков событий вызывается, чтобы позволить им обрабатывать это событие один за другим. Вам не нужно вызывать их самостоятельно, хотя вы можете сделать это во многих случаях, чтобы легко имитировать происходящее событие. Например, учитывая объект кнопки myButton , вы можете сделать myButton.onclick(myEventObject) для прямого вызова обработчика событий. Если обработчик событий не имеет доступа к каким-либо данным из объекта event, вы можете пропустить это событие при вызове функции onclick() .

+ +

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.

+ +

Это продолжается до тех пор, пока не будет вызван каждый обработчик, если только один из обработчиков событий явно не остановит обработку события, вызвав {{domxref("Event.stopPropagation", " stopPropagation ()")}} на самом объекте события.

+ +

Non-element objects

+ +

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 progress event on instances of XMLHttpRequest:

+ +
const xhr = new XMLHttpRequest();
+xhr.onprogress = function() { … };
+ +

HTML onevent attributes

+ +

HTML elements have attributes named onevent 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 onevent 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.

+ +

Further changes to the HTML attribute value can be done via the setAttribute method; Making changes to the JavaScript property will have no effect.

+ +

HTML

+ +

Given this HTML document:

+ +
<p>Demonstrating quirks of <code>on<em>event</em></code> HTML attributes on
+   <a onclick="log('Click!')">these three words</a>.
+</p>
+
+<div></div>
+ +

JavaScript

+ +

Then this JavaScript demonstrates that the value of the HTML attribute is unaffected by changes to the JavaScript object's property.

+ +
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>`);
+ +

Result

+ +

{{ EmbedLiveSample('HTML_onevent_attributes', '', '', '', 'Web/Guide/Events/Event_handlers') }}

+ +

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: onblur, onerror, onfocus, onload, and onscroll.)

+ +

Event handler's parameters, this binding, and the return value

+ +

When the event handler is specified as an HTML attribute, the specified code is wrapped into a function with the following parameters:

+ +
    +
  • event — for all event handlers except {{domxref("GlobalEventHandlers.onerror", "onerror")}}.
  • +
  • event, source, lineno, colno, and error for the {{domxref("GlobalEventHandlers.onerror", "onerror")}} event handler. Note that the event parameter actually contains the error message as a string.
  • +
+ +

When the event handler is invoked, the this keyword inside the handler is set to the DOM element on which the handler is registered. For more details, see the this keyword documentation.

+ +

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 "The event handler processing algorithm" in the HTML specification.

+ +

When the event handler is invoked

+ +
+

TBD (non-capturing listener)

+
+ +

Terminology

+ +

The term event handler may refer to:

+ +
    +
  • Any function or object that is registered to be notified of events
  • +
  • Or more specifically, to the mechanism of registering event listeners via on… attributes in HTML or properties in Web APIs, such as <button onclick="alert(this)"> or window.onload = function() { … }.
  • +
+ +

When discussing the various methods of listening to events:

+ +
    +
  • Event listener refers to a function or object registered via {{domxref("EventTarget.addEventListener()")}}
  • +
  • Event handler refers to a function registered via on… attributes or properties
  • +
+ +

Specifications

+ + + + +
Specif