From d2e114b94b7224a23f59376d6c92c069a9c907bf Mon Sep 17 00:00:00 2001 From: wbamberg Date: Tue, 12 Sep 2023 16:30:08 -0700 Subject: [PATCH] Merge usage notes and other notes --- .../api/eventtarget/addeventlistener/index.md | 1176 ++++++++--------- 1 file changed, 588 insertions(+), 588 deletions(-) diff --git a/files/en-us/web/api/eventtarget/addeventlistener/index.md b/files/en-us/web/api/eventtarget/addeventlistener/index.md index e0ec181c84fd648..74761a016de78d3 100644 --- a/files/en-us/web/api/eventtarget/addeventlistener/index.md +++ b/files/en-us/web/api/eventtarget/addeventlistener/index.md @@ -205,779 +205,779 @@ You can learn more in the [Implementing feature detection](/en-US/docs/Learn/Too [`EventListenerOptions`](https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md#feature-detection) from the [Web Incubator Community Group](https://wicg.github.io/admin/charter.html). -## Examples +### The value of "this" within the handler -### Add a simple listener +It is often desirable to reference the element on which the event handler was fired, +such as when using a generic handler for a set of similar elements. -This example demonstrates how to use `addEventListener()` to watch for mouse -clicks on an element. +When attaching a handler function to an element using `addEventListener()`, +the value of {{jsxref("Operators/this","this")}} inside the handler will be a reference to +the element. It will be the same as the value of the `currentTarget` property of +the event argument that is passed to the handler. -#### HTML +```js +my_element.addEventListener("click", function (e) { + console.log(this.className); // logs the className of my_element + console.log(e.currentTarget === this); // logs `true` +}); +``` + +As a reminder, [arrow functions do not have their own `this` context](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#cannot_be_used_as_methods). + +```js +my_element.addEventListener("click", (e) => { + console.log(this.className); // WARNING: `this` is not `my_element` + console.log(e.currentTarget === this); // logs `false` +}); +``` + +If an event handler (for example, {{domxref("Element.click_event", + "onclick")}}) is specified on an element in the HTML source, the JavaScript code in the +attribute value is effectively wrapped in a handler function that binds the value of +`this` in a manner consistent with the `addEventListener()`; an +occurrence of `this` within the code represents a reference to the element. ```html - - - - - - - +
one
two
+ + …
``` -#### JavaScript - -```js -// Function to change the content of t2 -function modifyText() { - const t2 = document.getElementById("t2"); - const isNodeThree = t2.firstChild.nodeValue === "three"; - t2.firstChild.nodeValue = isNodeThree ? "two" : "three"; -} +Note that the value of `this` inside a function, _called by_ the code +in the attribute value, behaves as per [standard rules](/en-US/docs/Web/JavaScript/Reference/Operators/this). This is +shown in the following example: -// Add event listener to table -const el = document.getElementById("outside"); -el.addEventListener("click", modifyText, false); +```html + + + + … +
``` -In this code, `modifyText()` is a listener for `click` events -registered using `addEventListener()`. A click anywhere in the table bubbles -up to the handler and runs `modifyText()`. +The value of `this` within `logID()` is a reference to the global +object {{domxref("Window")}} (or `undefined` in the case of [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode). -#### Result +#### Specifying "this" using bind() -{{EmbedLiveSample('Add_a_simple_listener')}} +The {{jsxref("Function.prototype.bind()")}} method lets you establish a fixed +`this` context for all subsequent calls — bypassing problems where it's unclear what `this` will be, depending on +the context from which your function was called. Note, however, that you'll need to keep +a reference to the listener around so you can remove it later. -### Add an abortable listener +This is an example with and without `bind()`: -This example demonstrates how to add an `addEventListener()` that can be aborted with an {{domxref("AbortSignal")}}. +```js +const Something = function (element) { + // |this| is a newly created object + this.name = "Something Good"; + this.onclick1 = function (event) { + console.log(this.name); // undefined, as |this| is the element + }; -#### HTML + this.onclick2 = function (event) { + console.log(this.name); // 'Something Good', as |this| is bound to newly created object + }; -```html - - - - - - - -
one
two
+ // bind causes a fixed `this` context to be assigned to onclick2 + this.onclick2 = this.onclick2.bind(this); + + element.addEventListener("click", this.onclick1, false); + element.addEventListener("click", this.onclick2, false); // Trick +}; +const s = new Something(document.body); ``` -#### JavaScript +Another solution is using a special function called `handleEvent()` to catch +any events: ```js -// Add an abortable event listener to table -const controller = new AbortController(); -const el = document.getElementById("outside"); -el.addEventListener("click", modifyText, { signal: controller.signal }); +const Something = function (element) { + // |this| is a newly created object + this.name = "Something Good"; + this.handleEvent = function (event) { + console.log(this.name); // 'Something Good', as this is bound to newly created object + switch (event.type) { + case "click": + // some code here… + break; + case "dblclick": + // some code here… + break; + } + }; -// Function to change the content of t2 -function modifyText() { - const t2 = document.getElementById("t2"); - if (t2.firstChild.nodeValue === "three") { - t2.firstChild.nodeValue = "two"; - } else { - t2.firstChild.nodeValue = "three"; - controller.abort(); // remove listener after value reaches "three" - } -} + // Note that the listeners in this case are |this|, not this.handleEvent + element.addEventListener("click", this, false); + element.addEventListener("dblclick", this, false); + + // You can properly remove the listeners + element.removeEventListener("click", this, false); + element.removeEventListener("dblclick", this, false); +}; +const s = new Something(document.body); ``` -In the example above, we modify the code in the previous example such that after the second row's content changes to "three", we call `abort()` from the {{domxref("AbortController")}} we passed to the `addEventListener()` call. That results in the value remaining as "three" forever because we no longer have any code listening for a click event. +Another way of handling the reference to _this_ is to pass to the +`EventListener` a function that calls the method of the object that contains +the fields that need to be accessed: -#### Result +```js +class SomeClass { + constructor() { + this.name = "Something Good"; + } -{{EmbedLiveSample('Add_an_abortable_listener')}} + register() { + const that = this; + window.addEventListener("keydown", (e) => { + that.someMethod(e); + }); + } -### Event listener with anonymous function + someMethod(e) { + console.log(this.name); + switch (e.keyCode) { + case 5: + // some code here… + break; + case 6: + // some code here… + break; + } + } +} -Here, we'll take a look at how to use an anonymous function to pass parameters into the -event listener. +const myObject = new SomeClass(); +myObject.register(); +``` -#### HTML +### Getting data into and out of an event listener -```html - - - - - - - -
one
two
-``` +It may seem that event listeners are like islands, and that it is extremely difficult +to pass them any data, much less to get any data back from them after they execute. +Event listeners only take one argument, +the [Event Object](/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_objects), +which is automatically passed to the listener, and the return value is ignored. +So how can we get data in and back out of them? There are a number of +good methods for doing this. -#### JavaScript +#### Getting data into an event listener using "this" + +As mentioned [above](#specifying_this_using_bind), you can use +`Function.prototype.bind()` to pass a value to an event listener via the +`this` reference variable. ```js -// Function to change the content of t2 -function modifyText(new_text) { - const t2 = document.getElementById("t2"); - t2.firstChild.nodeValue = new_text; -} +const myButton = document.getElementById("my-button-id"); +const someString = "Data"; -// Function to add event listener to table -const el = document.getElementById("outside"); -el.addEventListener( +myButton.addEventListener( "click", function () { - modifyText("four"); - }, - false, + console.log(this); // Expected Value: 'Data' + }.bind(someString), ); ``` -Notice that the listener is an anonymous function that encapsulates code that is then, -in turn, able to send parameters to the `modifyText()` function, which is -responsible for actually responding to the event. +This method is suitable when you don't need to know which HTML element the event +listener fired on programmatically from within the event listener. The primary benefit +to doing this is that the event listener receives the data in much the same way that it +would if you were to actually pass it through its argument list. -#### Result +#### Getting data into an event listener using the outer scope property -{{EmbedLiveSample('Event_listener_with_anonymous_function')}} +When an outer scope contains a variable declaration (with `const`, +`let`), all the inner functions declared in that scope have access to that +variable (look [here](/en-US/docs/Glossary/Function#different_types_of_functions) for +information on outer/inner functions, and [here](/en-US/docs/Web/JavaScript/Reference/Statements/var#implicit_globals_and_outer_function_scope) +for information on variable scope). Therefore, one of the simplest ways to access data +from outside of an event listener is to make it accessible to the scope in which the +event listener is declared. -### Event listener with an arrow function +```js +const myButton = document.getElementById("my-button-id"); +let someString = "Data"; -This example demonstrates a simple event listener implemented using arrow function -notation. +myButton.addEventListener("click", () => { + console.log(someString); // Expected Value: 'Data' -#### HTML + someString = "Data Again"; +}); -```html - - - - - - - -
one
two
+console.log(someString); // Expected Value: 'Data' (will never output 'Data Again') ``` -#### JavaScript - -```js -// Function to change the content of t2 -function modifyText(new_text) { - const t2 = document.getElementById("t2"); - t2.firstChild.nodeValue = new_text; -} +> **Note:** Although inner scopes have access to `const`, +> `let` variables from outer scopes, you cannot expect any changes to these +> variables to be accessible after the event listener definition, within the same outer +> scope. Why? Because by the time the event listener would execute, the scope in which +> it was defined would have already finished executing. -// Add event listener to table with an arrow function -const el = document.getElementById("outside"); -el.addEventListener( - "click", - () => { - modifyText("four"); - }, - false, -); -``` +#### Getting data into and out of an event listener using objects -#### Result +Unlike most functions in JavaScript, objects are retained in memory as long as a +variable referencing them exists in memory. This, and the fact that objects can have +properties, and that they can be passed around by reference, makes them likely +candidates for sharing data among scopes. Let's explore this. -{{EmbedLiveSample('Event_listener_with_an_arrow_function')}} +> **Note:** Functions in JavaScript are actually objects. (Hence they too +> can have properties, and will be retained in memory even after they finish executing +> if assigned to a variable that persists in memory.) -Please note that while anonymous and arrow functions are similar, they have different -`this` bindings. While anonymous (and all traditional JavaScript functions) -create their own `this` bindings, arrow functions inherit the -`this` binding of the containing function. +Because object properties can be used to store data in memory as long as a variable +referencing the object exists in memory, you can actually use them to get data into an +event listener, and any changes to the data back out after an event handler executes. +Consider this example. -That means that the variables and constants available to the containing function are -also available to the event handler when using an arrow function. +```js +const myButton = document.getElementById("my-button-id"); +const someObject = { aProperty: "Data" }; -### Example of options usage +myButton.addEventListener("click", () => { + console.log(someObject.aProperty); // Expected Value: 'Data' -#### HTML + someObject.aProperty = "Data Again"; // Change the value +}); -```html -
- outer, once & none-once - -
+setInterval(() => { + if (someObject.aProperty === "Data Again") { + console.log("Data Again: True"); + someObject.aProperty = "Data"; // Reset value to wait for next event execution + } +}, 5000); ``` -#### CSS +In this example, even though the scope in which both the event listener and the +interval function are defined would have finished executing before the original value of +`someObject.aProperty` would have changed, because `someObject` +persists in memory (by _reference_) in both the event listener and interval +function, both have access to the same data (i.e. when one changes the data, the other +can respond to the change). -```css -.outer, -.middle, -.inner1, -.inner2 { - display: block; - width: 520px; - padding: 15px; - margin: 15px; - text-decoration: none; -} -.outer { - border: 1px solid red; - color: red; +> **Note:** Objects are stored in variables by reference, meaning only the +> memory location of the actual data is stored in the variable. Among other things, this +> means variables that "store" objects can actually affect other variables that get +> assigned ("store") the same object reference. When two variables reference the same +> object (e.g., `let a = b = {aProperty: 'Yeah'};`), changing the data in +> either variable will affect the other. + +> **Note:** Because objects are stored in variables by reference, you can +> return an object from a function to keep it alive (preserve it in memory so you don't +> lose the data) after that function stops executing. + +### Memory issues + +```js +const elts = document.getElementsByTagName("*"); + +// Case 1 +for (const elt of elts) { + elt.addEventListener( + "click", + (e) => { + // Do something + }, + false, + ); } -.middle { - border: 1px solid green; - color: green; - width: 460px; + +// Case 2 +function processEvent(e) { + // Do something } -.inner1, -.inner2 { - border: 1px solid purple; - color: purple; - width: 400px; + +for (const elt of elts) { + elt.addEventListener("click", processEvent, false); } ``` -#### JavaScript +In the first case above, a new (anonymous) handler function is created with each +iteration of the loop. In the second case, the same previously declared function is used +as an event handler, which results in smaller memory consumption because there is only +one handler function created. Moreover, in the first case, it is not possible to call +{{domxref("EventTarget.removeEventListener", "removeEventListener()")}} because no +reference to the anonymous function is kept (or here, not kept to any of the multiple +anonymous functions the loop might create.) In the second case, it's possible to do +`myElement.removeEventListener("click", processEvent, false)` +because `processEvent` is the function reference. -```js -const outer = document.querySelector(".outer"); -const middle = document.querySelector(".middle"); -const inner1 = document.querySelector(".inner1"); -const inner2 = document.querySelector(".inner2"); +Actually, regarding memory consumption, the lack of keeping a function reference is not +the real issue; rather it is the lack of keeping a _static_ function reference. -const capture = { - capture: true, -}; -const noneCapture = { - capture: false, -}; -const once = { - once: true, -}; -const noneOnce = { - once: false, -}; -const passive = { - passive: true, -}; -const nonePassive = { - passive: false, -}; +### Using passive listeners -outer.addEventListener("click", onceHandler, once); -outer.addEventListener("click", noneOnceHandler, noneOnce); -middle.addEventListener("click", captureHandler, capture); -middle.addEventListener("click", noneCaptureHandler, noneCapture); -inner1.addEventListener("click", passiveHandler, passive); -inner2.addEventListener("click", nonePassiveHandler, nonePassive); +If an event has a default action — for example, a {{domxref("Element/wheel_event", "wheel")}} event that scrolls the container by default — the browser is in general unable to start the default action until the event listener has finished, because it doesn't know in advance whether the event listener might cancel the default action by calling {{domxref("Event.preventDefault()")}}. If the event listener takes too long to execute, this can cause a noticeable delay, also known as {{glossary("jank")}}, before the default action can be executed. -function onceHandler(event) { - alert("outer, once"); -} -function noneOnceHandler(event) { - alert("outer, none-once, default"); -} -function captureHandler(event) { - //event.stopImmediatePropagation(); - alert("middle, capture"); -} -function noneCaptureHandler(event) { - alert("middle, none-capture, default"); -} -function passiveHandler(event) { - // Unable to preventDefault inside passive event listener invocation. - event.preventDefault(); - alert("inner1, passive, open new page"); -} -function nonePassiveHandler(event) { - event.preventDefault(); - //event.stopPropagation(); - alert("inner2, none-passive, default, not open new page"); -} -``` +By setting the `passive` option to `true`, an event listener declares that it will not cancel the default action, so the browser can start the default action immediately, without waiting for the listener to finish. If the listener does then call {{domxref("Event.preventDefault()")}}, this will have no effect. -#### Result +The specification for `addEventListener()` defines the default value for the `passive` option as always being `false`. However, to realize the scroll performance benefits of passive listeners in legacy code, browsers other than Safari have changed the default value of the `passive` option to `true` for the {{domxref("Element/wheel_event", "wheel")}}, {{domxref("Element/mousewheel_event", "mousewheel")}}, {{domxref("Element/touchstart_event", "touchstart")}} and {{domxref("Element/touchmove_event", "touchmove")}} events on the document-level nodes {{domxref("Window")}}, {{domxref("Document")}}, and {{domxref("Document.body")}}. That prevents the event listener from [canceling the event](/en-US/docs/Web/API/Event/preventDefault), so it can't block page rendering while the user is scrolling. -Click the outer, middle, inner containers respectively to see how the options work. +> **Note:** See the compatibility table below if you need to know which +> browsers (and/or which versions of those browsers) implement this altered behavior. -{{ EmbedLiveSample('Example_of_options_usage', 600, 310, '') }} +Because of that, when you want to override that behavior and ensure the `passive` option is `false` in all browsers, you must explicitly set the option to `false` (rather than relying on the default). -Before using a particular value in the `options` object, it's a -good idea to ensure that the user's browser supports it, since these are an addition -that not all browsers have supported historically. See [Safely detecting option support](#safely_detecting_option_support) for details. +You don't need to worry about the value of `passive` for the basic {{domxref("Element/scroll_event", "scroll")}} event. +Since it can't be canceled, event listeners can't block page rendering anyway. -### Event listener with multiple options +See [Improving scroll performance using passive listeners](#improving_scroll_performance_using_passive_listeners) for an example showing the effect of passive listeners. -You can set more than one of the options in the `options` parameter. In the following example we are setting two options: +### Older browsers -- `passive`, to assert that the handler will not call {{domxref("Event.preventDefault", "preventDefault()")}} -- `once`, to ensure that the event handler will only be called once. +In older browsers that don't support the `options` parameter to +`addEventListener()`, attempting to use it prevents the use of the +`useCapture` argument without proper use of [feature detection](#safely_detecting_option_support). + +## Examples + +### Add a simple listener + +This example demonstrates how to use `addEventListener()` to watch for mouse +clicks on an element. #### HTML ```html - - + + + + + + + +
one
two
``` #### JavaScript ```js -const buttonToBeClicked = document.getElementById("example-button"); - -const resetButton = document.getElementById("reset-button"); +// Function to change the content of t2 +function modifyText() { + const t2 = document.getElementById("t2"); + const isNodeThree = t2.firstChild.nodeValue === "three"; + t2.firstChild.nodeValue = isNodeThree ? "two" : "three"; +} -// the text that the button is initialized with -const initialText = buttonToBeClicked.textContent; - -// the text that the button contains after being clicked -const clickedText = "You have clicked this button."; - -// we hoist the event listener callback function -// to prevent having duplicate listeners attached -function eventListener() { - buttonToBeClicked.textContent = clickedText; -} - -function addListener() { - buttonToBeClicked.addEventListener("click", eventListener, { - passive: true, - once: true, - }); -} - -// when the reset button is clicked, the example button is reset, -// and allowed to have its state updated again -resetButton.addEventListener("click", () => { - buttonToBeClicked.textContent = initialText; - addListener(); -}); - -addListener(); +// Add event listener to table +const el = document.getElementById("outside"); +el.addEventListener("click", modifyText, false); ``` +In this code, `modifyText()` is a listener for `click` events +registered using `addEventListener()`. A click anywhere in the table bubbles +up to the handler and runs `modifyText()`. + #### Result -{{EmbedLiveSample('Event_listener_with_multiple_options')}} +{{EmbedLiveSample('Add_a_simple_listener')}} -### Improving scroll performance using passive listeners +### Add an abortable listener -The following example shows the effect of setting `passive`. It includes a {{htmlelement("div")}} that contains some text, and a check box. +This example demonstrates how to add an `addEventListener()` that can be aborted with an {{domxref("AbortSignal")}}. #### HTML ```html -
-

- But down there it would be dark now, and not the lovely lighted aquarium she - imagined it to be during the daylight hours, eddying with schools of tiny, - delicate animals floating and dancing slowly to their own serene currents - and creating the look of a living painting. That was wrong, in any case. The - ocean was different from an aquarium, which was an artificial environment. - The ocean was a world. And a world is not art. Dorothy thought about the - living things that moved in that world: large, ruthless and hungry. Like us - up here. -

-
- -
- - -
-``` - -```css hidden -#container { - width: 150px; - height: 200px; - overflow: scroll; - margin: 2rem 0; - padding: 0.4rem; - border: 1px solid black; -} + + + + + + + +
one
two
``` #### JavaScript -The code adds a listener to the container's {{domxref("Element/wheel_event", "wheel")}} event, which by default scrolls the container. The listener runs a long-running operation. Initially the listener is added with the `passive` option, and whenever the checkbox is toggled, the code toggles the `passive` option. - ```js -const passive = document.querySelector("#passive"); -passive.addEventListener("change", (event) => { - container.removeEventListener("wheel", wheelHandler); - container.addEventListener("wheel", wheelHandler, { - passive: passive.checked, - once: true, - }); -}); - -const container = document.querySelector("#container"); -container.addEventListener("wheel", wheelHandler, { - passive: true, - once: true, -}); - -function wheelHandler() { - function isPrime(n) { - for (let c = 2; c <= Math.sqrt(n); ++c) { - if (n % c === 0) { - return false; - } - } - return true; - } - - const quota = 1000000; - const primes = []; - const maximum = 1000000; +// Add an abortable event listener to table +const controller = new AbortController(); +const el = document.getElementById("outside"); +el.addEventListener("click", modifyText, { signal: controller.signal }); - while (primes.length < quota) { - const candidate = Math.floor(Math.random() * (maximum + 1)); - if (isPrime(candidate)) { - primes.push(candidate); - } +// Function to change the content of t2 +function modifyText() { + const t2 = document.getElementById("t2"); + if (t2.firstChild.nodeValue === "three") { + t2.firstChild.nodeValue = "two"; + } else { + t2.firstChild.nodeValue = "three"; + controller.abort(); // remove listener after value reaches "three" } - - console.log(primes); } ``` -#### Result +In the example above, we modify the code in the previous example such that after the second row's content changes to "three", we call `abort()` from the {{domxref("AbortController")}} we passed to the `addEventListener()` call. That results in the value remaining as "three" forever because we no longer have any code listening for a click event. -The effect is that: +#### Result -- Initially, the listener is passive, so trying to scroll the container with the wheel is immediate. -- If you uncheck "passive" and try to scroll the container using the wheel, then there is a noticeable delay before the container scrolls, because the browser has to wait for the long-running listener to finish. +{{EmbedLiveSample('Add_an_abortable_listener')}} -{{EmbedLiveSample("Improving scroll performance using passive listeners", 100, 300)}} +### Event listener with anonymous function -## Other notes +Here, we'll take a look at how to use an anonymous function to pass parameters into the +event listener. -### The value of "this" within the handler +#### HTML -It is often desirable to reference the element on which the event handler was fired, -such as when using a generic handler for a set of similar elements. +```html + + + + + + + +
one
two
+``` -When attaching a handler function to an element using `addEventListener()`, -the value of {{jsxref("Operators/this","this")}} inside the handler will be a reference to -the element. It will be the same as the value of the `currentTarget` property of -the event argument that is passed to the handler. +#### JavaScript ```js -my_element.addEventListener("click", function (e) { - console.log(this.className); // logs the className of my_element - console.log(e.currentTarget === this); // logs `true` -}); +// Function to change the content of t2 +function modifyText(new_text) { + const t2 = document.getElementById("t2"); + t2.firstChild.nodeValue = new_text; +} + +// Function to add event listener to table +const el = document.getElementById("outside"); +el.addEventListener( + "click", + function () { + modifyText("four"); + }, + false, +); ``` -As a reminder, [arrow functions do not have their own `this` context](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#cannot_be_used_as_methods). +Notice that the listener is an anonymous function that encapsulates code that is then, +in turn, able to send parameters to the `modifyText()` function, which is +responsible for actually responding to the event. -```js -my_element.addEventListener("click", (e) => { - console.log(this.className); // WARNING: `this` is not `my_element` - console.log(e.currentTarget === this); // logs `false` -}); -``` +#### Result -If an event handler (for example, {{domxref("Element.click_event", - "onclick")}}) is specified on an element in the HTML source, the JavaScript code in the -attribute value is effectively wrapped in a handler function that binds the value of -`this` in a manner consistent with the `addEventListener()`; an -occurrence of `this` within the code represents a reference to the element. +{{EmbedLiveSample('Event_listener_with_anonymous_function')}} -```html - - - … -
-``` +### Event listener with an arrow function -Note that the value of `this` inside a function, _called by_ the code -in the attribute value, behaves as per [standard rules](/en-US/docs/Web/JavaScript/Reference/Operators/this). This is -shown in the following example: +This example demonstrates a simple event listener implemented using arrow function +notation. + +#### HTML ```html - - - - … +
+ + + + + +
one
two
``` -The value of `this` within `logID()` is a reference to the global -object {{domxref("Window")}} (or `undefined` in the case of [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode). +#### JavaScript -#### Specifying "this" using bind() +```js +// Function to change the content of t2 +function modifyText(new_text) { + const t2 = document.getElementById("t2"); + t2.firstChild.nodeValue = new_text; +} -The {{jsxref("Function.prototype.bind()")}} method lets you establish a fixed -`this` context for all subsequent calls — bypassing problems where it's unclear what `this` will be, depending on -the context from which your function was called. Note, however, that you'll need to keep -a reference to the listener around so you can remove it later. +// Add event listener to table with an arrow function +const el = document.getElementById("outside"); +el.addEventListener( + "click", + () => { + modifyText("four"); + }, + false, +); +``` -This is an example with and without `bind()`: +#### Result -```js -const Something = function (element) { - // |this| is a newly created object - this.name = "Something Good"; - this.onclick1 = function (event) { - console.log(this.name); // undefined, as |this| is the element - }; +{{EmbedLiveSample('Event_listener_with_an_arrow_function')}} - this.onclick2 = function (event) { - console.log(this.name); // 'Something Good', as |this| is bound to newly created object - }; +Please note that while anonymous and arrow functions are similar, they have different +`this` bindings. While anonymous (and all traditional JavaScript functions) +create their own `this` bindings, arrow functions inherit the +`this` binding of the containing function. - // bind causes a fixed `this` context to be assigned to onclick2 - this.onclick2 = this.onclick2.bind(this); +That means that the variables and constants available to the containing function are +also available to the event handler when using an arrow function. - element.addEventListener("click", this.onclick1, false); - element.addEventListener("click", this.onclick2, false); // Trick -}; -const s = new Something(document.body); -``` +### Example of options usage -Another solution is using a special function called `handleEvent()` to catch -any events: +#### HTML -```js -const Something = function (element) { - // |this| is a newly created object - this.name = "Something Good"; - this.handleEvent = function (event) { - console.log(this.name); // 'Something Good', as this is bound to newly created object - switch (event.type) { - case "click": - // some code here… - break; - case "dblclick": - // some code here… - break; - } - }; +```html +
+ outer, once & none-once + +
+``` - // Note that the listeners in this case are |this|, not this.handleEvent - element.addEventListener("click", this, false); - element.addEventListener("dblclick", this, false); +#### CSS - // You can properly remove the listeners - element.removeEventListener("click", this, false); - element.removeEventListener("dblclick", this, false); -}; -const s = new Something(document.body); +```css +.outer, +.middle, +.inner1, +.inner2 { + display: block; + width: 520px; + padding: 15px; + margin: 15px; + text-decoration: none; +} +.outer { + border: 1px solid red; + color: red; +} +.middle { + border: 1px solid green; + color: green; + width: 460px; +} +.inner1, +.inner2 { + border: 1px solid purple; + color: purple; + width: 400px; +} ``` -Another way of handling the reference to _this_ is to pass to the -`EventListener` a function that calls the method of the object that contains -the fields that need to be accessed: +#### JavaScript ```js -class SomeClass { - constructor() { - this.name = "Something Good"; - } +const outer = document.querySelector(".outer"); +const middle = document.querySelector(".middle"); +const inner1 = document.querySelector(".inner1"); +const inner2 = document.querySelector(".inner2"); - register() { - const that = this; - window.addEventListener("keydown", (e) => { - that.someMethod(e); - }); - } +const capture = { + capture: true, +}; +const noneCapture = { + capture: false, +}; +const once = { + once: true, +}; +const noneOnce = { + once: false, +}; +const passive = { + passive: true, +}; +const nonePassive = { + passive: false, +}; - someMethod(e) { - console.log(this.name); - switch (e.keyCode) { - case 5: - // some code here… - break; - case 6: - // some code here… - break; - } - } +outer.addEventListener("click", onceHandler, once); +outer.addEventListener("click", noneOnceHandler, noneOnce); +middle.addEventListener("click", captureHandler, capture); +middle.addEventListener("click", noneCaptureHandler, noneCapture); +inner1.addEventListener("click", passiveHandler, passive); +inner2.addEventListener("click", nonePassiveHandler, nonePassive); + +function onceHandler(event) { + alert("outer, once"); +} +function noneOnceHandler(event) { + alert("outer, none-once, default"); +} +function captureHandler(event) { + //event.stopImmediatePropagation(); + alert("middle, capture"); +} +function noneCaptureHandler(event) { + alert("middle, none-capture, default"); +} +function passiveHandler(event) { + // Unable to preventDefault inside passive event listener invocation. + event.preventDefault(); + alert("inner1, passive, open new page"); +} +function nonePassiveHandler(event) { + event.preventDefault(); + //event.stopPropagation(); + alert("inner2, none-passive, default, not open new page"); } - -const myObject = new SomeClass(); -myObject.register(); ``` -### Getting data into and out of an event listener - -It may seem that event listeners are like islands, and that it is extremely difficult -to pass them any data, much less to get any data back from them after they execute. -Event listeners only take one argument, -the [Event Object](/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_objects), -which is automatically passed to the listener, and the return value is ignored. -So how can we get data in and back out of them? There are a number of -good methods for doing this. - -#### Getting data into an event listener using "this" - -As mentioned [above](#specifying_this_using_bind), you can use -`Function.prototype.bind()` to pass a value to an event listener via the -`this` reference variable. - -```js -const myButton = document.getElementById("my-button-id"); -const someString = "Data"; +#### Result -myButton.addEventListener( - "click", - function () { - console.log(this); // Expected Value: 'Data' - }.bind(someString), -); -``` +Click the outer, middle, inner containers respectively to see how the options work. -This method is suitable when you don't need to know which HTML element the event -listener fired on programmatically from within the event listener. The primary benefit -to doing this is that the event listener receives the data in much the same way that it -would if you were to actually pass it through its argument list. +{{ EmbedLiveSample('Example_of_options_usage', 600, 310, '') }} -#### Getting data into an event listener using the outer scope property +Before using a particular value in the `options` object, it's a +good idea to ensure that the user's browser supports it, since these are an addition +that not all browsers have supported historically. See [Safely detecting option support](#safely_detecting_option_support) for details. -When an outer scope contains a variable declaration (with `const`, -`let`), all the inner functions declared in that scope have access to that -variable (look [here](/en-US/docs/Glossary/Function#different_types_of_functions) for -information on outer/inner functions, and [here](/en-US/docs/Web/JavaScript/Reference/Statements/var#implicit_globals_and_outer_function_scope) -for information on variable scope). Therefore, one of the simplest ways to access data -from outside of an event listener is to make it accessible to the scope in which the -event listener is declared. +### Event listener with multiple options -```js -const myButton = document.getElementById("my-button-id"); -let someString = "Data"; +You can set more than one of the options in the `options` parameter. In the following example we are setting two options: -myButton.addEventListener("click", () => { - console.log(someString); // Expected Value: 'Data' +- `passive`, to assert that the handler will not call {{domxref("Event.preventDefault", "preventDefault()")}} +- `once`, to ensure that the event handler will only be called once. - someString = "Data Again"; -}); +#### HTML -console.log(someString); // Expected Value: 'Data' (will never output 'Data Again') +```html + + ``` -> **Note:** Although inner scopes have access to `const`, -> `let` variables from outer scopes, you cannot expect any changes to these -> variables to be accessible after the event listener definition, within the same outer -> scope. Why? Because by the time the event listener would execute, the scope in which -> it was defined would have already finished executing. +#### JavaScript -#### Getting data into and out of an event listener using objects +```js +const buttonToBeClicked = document.getElementById("example-button"); -Unlike most functions in JavaScript, objects are retained in memory as long as a -variable referencing them exists in memory. This, and the fact that objects can have -properties, and that they can be passed around by reference, makes them likely -candidates for sharing data among scopes. Let's explore this. +const resetButton = document.getElementById("reset-button"); -> **Note:** Functions in JavaScript are actually objects. (Hence they too -> can have properties, and will be retained in memory even after they finish executing -> if assigned to a variable that persists in memory.) +// the text that the button is initialized with +const initialText = buttonToBeClicked.textContent; -Because object properties can be used to store data in memory as long as a variable -referencing the object exists in memory, you can actually use them to get data into an -event listener, and any changes to the data back out after an event handler executes. -Consider this example. +// the text that the button contains after being clicked +const clickedText = "You have clicked this button."; -```js -const myButton = document.getElementById("my-button-id"); -const someObject = { aProperty: "Data" }; +// we hoist the event listener callback function +// to prevent having duplicate listeners attached +function eventListener() { + buttonToBeClicked.textContent = clickedText; +} -myButton.addEventListener("click", () => { - console.log(someObject.aProperty); // Expected Value: 'Data' +function addListener() { + buttonToBeClicked.addEventListener("click", eventListener, { + passive: true, + once: true, + }); +} - someObject.aProperty = "Data Again"; // Change the value +// when the reset button is clicked, the example button is reset, +// and allowed to have its state updated again +resetButton.addEventListener("click", () => { + buttonToBeClicked.textContent = initialText; + addListener(); }); -setInterval(() => { - if (someObject.aProperty === "Data Again") { - console.log("Data Again: True"); - someObject.aProperty = "Data"; // Reset value to wait for next event execution - } -}, 5000); +addListener(); ``` -In this example, even though the scope in which both the event listener and the -interval function are defined would have finished executing before the original value of -`someObject.aProperty` would have changed, because `someObject` -persists in memory (by _reference_) in both the event listener and interval -function, both have access to the same data (i.e. when one changes the data, the other -can respond to the change). +#### Result -> **Note:** Objects are stored in variables by reference, meaning only the -> memory location of the actual data is stored in the variable. Among other things, this -> means variables that "store" objects can actually affect other variables that get -> assigned ("store") the same object reference. When two variables reference the same -> object (e.g., `let a = b = {aProperty: 'Yeah'};`), changing the data in -> either variable will affect the other. +{{EmbedLiveSample('Event_listener_with_multiple_options')}} -> **Note:** Because objects are stored in variables by reference, you can -> return an object from a function to keep it alive (preserve it in memory so you don't -> lose the data) after that function stops executing. +### Improving scroll performance using passive listeners -### Memory issues +The following example shows the effect of setting `passive`. It includes a {{htmlelement("div")}} that contains some text, and a check box. -```js -const elts = document.getElementsByTagName("*"); +#### HTML -// Case 1 -for (const elt of elts) { - elt.addEventListener( - "click", - (e) => { - // Do something - }, - false, - ); -} +```html +
+

+ But down there it would be dark now, and not the lovely lighted aquarium she + imagined it to be during the daylight hours, eddying with schools of tiny, + delicate animals floating and dancing slowly to their own serene currents + and creating the look of a living painting. That was wrong, in any case. The + ocean was different from an aquarium, which was an artificial environment. + The ocean was a world. And a world is not art. Dorothy thought about the + living things that moved in that world: large, ruthless and hungry. Like us + up here. +

+
-// Case 2 -function processEvent(e) { - // Do something -} +
+ + +
+``` -for (const elt of elts) { - elt.addEventListener("click", processEvent, false); +```css hidden +#container { + width: 150px; + height: 200px; + overflow: scroll; + margin: 2rem 0; + padding: 0.4rem; + border: 1px solid black; } ``` -In the first case above, a new (anonymous) handler function is created with each -iteration of the loop. In the second case, the same previously declared function is used -as an event handler, which results in smaller memory consumption because there is only -one handler function created. Moreover, in the first case, it is not possible to call -{{domxref("EventTarget.removeEventListener", "removeEventListener()")}} because no -reference to the anonymous function is kept (or here, not kept to any of the multiple -anonymous functions the loop might create.) In the second case, it's possible to do -`myElement.removeEventListener("click", processEvent, false)` -because `processEvent` is the function reference. +#### JavaScript -Actually, regarding memory consumption, the lack of keeping a function reference is not -the real issue; rather it is the lack of keeping a _static_ function reference. +The code adds a listener to the container's {{domxref("Element/wheel_event", "wheel")}} event, which by default scrolls the container. The listener runs a long-running operation. Initially the listener is added with the `passive` option, and whenever the checkbox is toggled, the code toggles the `passive` option. -### Using passive listeners +```js +const passive = document.querySelector("#passive"); +passive.addEventListener("change", (event) => { + container.removeEventListener("wheel", wheelHandler); + container.addEventListener("wheel", wheelHandler, { + passive: passive.checked, + once: true, + }); +}); -If an event has a default action — for example, a {{domxref("Element/wheel_event", "wheel")}} event that scrolls the container by default — the browser is in general unable to start the default action until the event listener has finished, because it doesn't know in advance whether the event listener might cancel the default action by calling {{domxref("Event.preventDefault()")}}. If the event listener takes too long to execute, this can cause a noticeable delay, also known as {{glossary("jank")}}, before the default action can be executed. +const container = document.querySelector("#container"); +container.addEventListener("wheel", wheelHandler, { + passive: true, + once: true, +}); -By setting the `passive` option to `true`, an event listener declares that it will not cancel the default action, so the browser can start the default action immediately, without waiting for the listener to finish. If the listener does then call {{domxref("Event.preventDefault()")}}, this will have no effect. +function wheelHandler() { + function isPrime(n) { + for (let c = 2; c <= Math.sqrt(n); ++c) { + if (n % c === 0) { + return false; + } + } + return true; + } -The specification for `addEventListener()` defines the default value for the `passive` option as always being `false`. However, to realize the scroll performance benefits of passive listeners in legacy code, browsers other than Safari have changed the default value of the `passive` option to `true` for the {{domxref("Element/wheel_event", "wheel")}}, {{domxref("Element/mousewheel_event", "mousewheel")}}, {{domxref("Element/touchstart_event", "touchstart")}} and {{domxref("Element/touchmove_event", "touchmove")}} events on the document-level nodes {{domxref("Window")}}, {{domxref("Document")}}, and {{domxref("Document.body")}}. That prevents the event listener from [canceling the event](/en-US/docs/Web/API/Event/preventDefault), so it can't block page rendering while the user is scrolling. + const quota = 1000000; + const primes = []; + const maximum = 1000000; -> **Note:** See the compatibility table below if you need to know which -> browsers (and/or which versions of those browsers) implement this altered behavior. + while (primes.length < quota) { + const candidate = Math.floor(Math.random() * (maximum + 1)); + if (isPrime(candidate)) { + primes.push(candidate); + } + } -Because of that, when you want to override that behavior and ensure the `passive` option is `false` in all browsers, you must explicitly set the option to `false` (rather than relying on the default). + console.log(primes); +} +``` -You don't need to worry about the value of `passive` for the basic {{domxref("Element/scroll_event", "scroll")}} event. -Since it can't be canceled, event listeners can't block page rendering anyway. +#### Result -### Older browsers +The effect is that: -In older browsers that don't support the `options` parameter to -`addEventListener()`, attempting to use it prevents the use of the -`useCapture` argument without proper use of [feature detection](#safely_detecting_option_support). +- Initially, the listener is passive, so trying to scroll the container with the wheel is immediate. +- If you uncheck "passive" and try to scroll the container using the wheel, then there is a noticeable delay before the container scrolls, because the browser has to wait for the long-running listener to finish. + +{{EmbedLiveSample("Improving scroll performance using passive listeners", 100, 300)}} ## Specifications