Eventtarget.addeventlistener() – web apis mdn electricity experiments elementary school

The EventTarget method addEventListener() sets up a function to be called whenever the specified event is delivered to the target. Common targets are Element, Document, and Window, but the target may be any object that supports events (such as XMLHttpRequest).

addEventListener() works by adding a function or an object that implements EventListener to the list of event listeners for the specified event type on the EventTarget on which it’s called. Syntax target.addEventListener( type, listener[, options]);

target.addEventListener( type, listener[, useCapture, wantsUntrusted ]); // Gecko/Mozilla only Parameters type A case-sensitive string representing the event type to listen for. listener The object which receives a notification (an object that implements the Event interface) when an event of the specified type occurs. This must be an object implementing the EventListener interface, or a JavaScript function. See The event listener callback for details on the callback itself. options Optional An options object that specifies characteristics about the event listener. The available options are:

useCapture Optional A Boolean indicating whether events of this type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree. Events that are bubbling upward through the tree will not trigger a listener designated to use capture. Event bubbling and capturing are two ways of propagating events which occur in an element that is nested within another element, when both elements have registered a handle for that event. The event propagation mode determines the order in which elements receive the event. See DOM Level 3 Events and JavaScript Event order for a detailed explanation. If not specified, useCapture defaults to false.

Note: useCapture has not always been optional. Ideally, you should include it for the widest possible browser compatibility. wantsUntrusted A Firefox (Gecko)-specific parameter. If true, the listener receives synthetic events dispatched by web content (the default is false for browser chrome and true for regular web pages). This parameter is useful for code found in add-ons as well as the browser itself. See Interaction between privileged and non-privileged pages for an example.

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 for details. Return value

In older versions of the DOM specification, the third parameter of addEventListener() was a Boolean value indicating whether or not to use capture. Over time, it became clear that more options were needed. Rather than adding more parameters to the function (complicating things enormously when dealing with optional values), the third parameter was changed to an object which can contain various properties defining the values of options to configure the process of removing the event listener.

Because older browsers (as well as some not-too-old browsers) still assume the third parameter is a Boolean, you need to build your code to handle this scenario intelligently. You can do this by using feature detection for each of the options you’re interested in.

This creates an options object with a getter function for the passive property; the getter sets a flag, passiveSupported, to true if it gets called. That means that if the browser checks the value of the passive property on the options object, passiveSupported will be set to true; otherwise, it will remain false. We then call addEventListener() to set up a fake event handler, specifying those options, so that the options will be checked if the browser recognizes an object as the third parameter. Then, we call removeEventListener() to clean up after ourselves. (Note that handleEvent() is ignored on event listeners that aren’t called.)

Here we’re adding a listener for the mouseup event on the element someElement. For the third parameter, if passiveSupported is true, we’re specifying an options object with passive set to true; otherwise, we know that we need to pass a Boolean, and we pass false as the value of the useCapture parameter.

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.

If an EventListener is added to an EventTarget while it is processing an event, that event does not trigger the listener. However, that same listener may be triggered during a later stage of event flow, such as the bubbling phase. Multiple identical event listeners

If multiple identical EventListeners are registered on the same EventTarget with the same parameters, the duplicate instances are discarded. They do not cause the EventListener to be called twice, and they do not need to be removed manually with the removeEventListener() method. The value of this within the handler

If attaching a handler function to an element using addEventListener(), the value of this inside the handler is a reference to the element. It is the same as the value of the currentTarget property of the event argument that is passed to the handler.

If an event handler (for example, onclick) is specified on an element in the HTML source, the JavaScript code in the attribute value is effectively wrapped in a handler function which 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. Note that the value of this inside a function, called by the code in the attribute value, behaves as per standard rules. This is shown in the following example:

The Function.prototype.bind() method lets you specify the value that should be used as this for all calls to a given function. This lets you easily bypass 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.

You can work around addEventListener(), removeEventListener(), Event.preventDefault(), and Event.stopPropagation() not being supported by Internet Explorer 8 by using the following code at the beginning of your script. The code supports the use of handleEvent() and also the DOMContentLoaded event.

Because it was essentially part of DOM 0, this technique for adding event listeners is very widely supported and requires no special cross–browser code. It is normally used to register event listeners dynamically unless the extra features of addEventListener() are needed. Memory issues var i;

In the first case, a new (anonymous) function is created with each iteration of the loop. In the second case, the same previously declared function is used as an event handler. This results in smaller memory consumption. Moreover, in the first case, it is not possible to call removeEventListener() because no reference to the anonymous function is kept. In the second case, it’s possible to do myElement.removeEventListener("click", processEvent, false). Improving scrolling performance with passive listeners

The default value for the passive option is false. Starting in Chrome 56 (desktop, Chrome for Android, and Android webview) the default value for touchstart and touchmove is true and calls to preventDefault() are not permitted. To override this behavior, you set the passive option to false as shown in the example below. This change prevents the listener from blocking page rendering while a user is scrolling. A demo is available on the Google Developer site. Please note that IE does not support the options argument at all, and adding it prevents the use of the useCapture argument without proper use of feature detection. /* Feature detection */