Notes Javascript - Events
EventTarget
The EventTarget interface is implemented by objects that can receive events and may have listeners for them. In other words, any target of events implements the three methods associated with this interface.
Element, and its children, as well as Document and Window, are the most common event targets, but other objects can be event targets, too. For example XMLHttpRequest, AudioNode, and AudioContext are also event targets.
Many event targets (including elements, documents, and windows) also support setting event handlers via onevent properties and attributes.
EventTarget() | Creates a new EventTarget object instance. |
---|
myEventTarget = new EventTarget()
class MyEventTarget extends EventTarget { constructor(mySecret) { super(); this._secret = mySecret; } get secret() { return this._secret; } } let myEventTarget = new MyEventTarget(5); let value = myEventTarget.secret; // === 5 myEventTarget.addEventListener("foo", (e) => { myEventTarget._secret = e.detail; }); let event = new CustomEvent("foo", { detail: 7 }); myEventTarget.dispatchEvent(event); let newValue = myEventTarget.secret; // === 7
EventTarget.addEventListener() | Registers an event handler of a specific event type on the EventTarget. |
---|---|
EventTarget.removeEventListener() | Removes an event listener from the EventTarget. |
EventTarget.dispatchEvent() | Dispatches an event to this EventTarget. |
addEventListener()
The addEventListener() method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target.
Common targets are Element, or its children, Document, and Window, but the target may be any object that supports events (such as XMLHttpRequest).
addEventListener(type, listener) addEventListener(type, listener, options) addEventListener(type, listener, useCapture)
Parameter | Description |
---|---|
type | A case-sensitive string representing the event type to listen for. |
listener | The object that receives a notification (an object that implements the Event interface) when an event of the specified type occurs. This must be null, an object with a handleEvent() method, or a JavaScript function. |
options |
An object that specifies characteristics about the event listener. The available options are: capture An optional boolean value indicating that events of this type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree. If not specified, defaults to false. once An optional boolean value indicating that the listener should be invoked at most once after being added. If true, the listener would be automatically removed when invoked. If not specified, defaults to false. passive An optional boolean value that, if true, indicates that the function specified by listener will never call preventDefault(). If a passive listener does call preventDefault(), the user agent will do nothing other than generate a console warning. If not specified, defaults to false - except that in browsers other than Safari, defaults to true for the wheel, mousewheel, touchstart and touchmove events. signal An optional AbortSignal. The listener will be removed when the given AbortSignal object's abort() method is called. If not specified, no AbortSignal is associated with the listener. |
useCapture | A boolean value 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 that 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. If not specified, useCapture defaults to false. |
removeEventListener()
The removeEventListener() method of the EventTarget interface removes an event listener previously registered with EventTarget.addEventListener() from the target. The event listener to be removed is identified using a combination of the event type, the event listener function itself, and various optional options that may affect the matching process; see Matching event listeners for removal.
Calling removeEventListener() with arguments that do not identify any currently registered event listener on the EventTarget has no effect.
If an event listener is removed from an EventTarget while another listener of the target is processing an event, it will not be triggered by the event. However, it can be reattached.
Warning: If a listener is registered twice, one with the capture flag set and one without, you must remove each one separately. Removal of a capturing listener does not affect a non-capturing version of the same listener, and vice versa.
Event listeners can also be removed by passing an AbortSignal to an addEventListener() and then later calling abort() on the controller owning the signal.
removeEventListener(type, listener) removeEventListener(type, listener, options) removeEventListener(type, listener, useCapture)
Parameter | Description |
---|---|
type | A string which specifies the type of event for which to remove an event listener. |
listener | The event listener function of the event handler to remove from the event target. |
options |
An options object that specifies characteristics about the event listener. The available options are: capture A boolean value that specifies whether the event listener to be removed is registered as a capturing listener or not. If this parameter is absent, the default value false is assumed. |
useCapture | A boolean value that specifies whether the event listener to be removed is registered as a capturing listener or not. If this parameter is absent, the default value false is assumed. |
Matching Event Listeners For Removal
Given an event listener previously added by calling addEventListener(), you may eventually come to a point
at which you need to remove it. Obviously, you need to specify the same type and listener parameters to
removeEventListener(). But what about the options or useCapture parameters?
While addEventListener() will let you add the same listener more than once for the same type if the options
are different, the only option removeEventListener() checks is the capture/useCapture flag. Its value must
match for removeEventListener() to match, but the other values don't.
For example, consider this call to addEventListener():
element.addEventListener("mousedown", handleMouseDown, true);
Now consider each of these two calls to removeEventListener():
element.removeEventListener("mousedown", handleMouseDown, false); // Fails element.removeEventListener("mousedown", handleMouseDown, true); // Succeeds
The first call fails because the value of useCapture doesn't match. The second succeeds, since useCapture matches up.
Now consider this:
element.addEventListener("mousedown", handleMouseDown, { passive: true });
Here, we specify an options object in which passive is set to true, while the other options are left to the default value of false.
Now look at each of these calls to removeEventListener() in turn. Any of them in which capture or useCapture is true fail; all others succeed.
Only the capture setting matters to removeEventListener().
element.removeEventListener("mousedown", handleMouseDown, { passive: true }); // Succeeds element.removeEventListener("mousedown", handleMouseDown, { capture: false }); // SUCCEEDS element.removeEventListener("mousedown", handleMouseDown, { capture: true }); // FAILS element.removeEventListener("mousedown", handleMouseDown, { passive: false }); // SUCCEEDS element.removeEventListener("mousedown", handleMouseDown, false); // SUCCEEDS element.removeEventListener("mousedown", handleMouseDown, true); // FAILS
It's worth noting that some browser releases have been inconsistent on this, and unless you have specific reasons otherwise, it's probably wise to use the same values used for the call to addEventListener() when calling removeEventListener().
Example
This example shows how to add a mouseover-based event listener that removes a click-based event listener.
const body = document.querySelector("body"); const clickTarget = document.getElementById("click-target"); const mouseOverTarget = document.getElementById("mouse-over-target"); let toggle = false; function makeBackgroundYellow() { body.style.backgroundColor = toggle ? "white" : "yellow"; toggle = !toggle; } clickTarget.addEventListener("click", makeBackgroundYellow, false); mouseOverTarget.addEventListener("mouseover", () => { clickTarget.removeEventListener("click", makeBackgroundYellow, false); });
dispatchEvent()
The dispatchEvent() method of the EventTarget sends an Event to the object, (synchronously) invoking the affected EventListeners in the appropriate order. The normal event processing rules (including the capturing and optional bubbling phase) also apply to events dispatched manually with dispatchEvent().
Calling dispatchEvent() is the last step to firing an event. The event should have already been created and initialized using an Event() constructor.
Note: When calling this method, the Event.target property is initialized to the current EventTarget.
Unlike "native" events, which are fired by the browser and invoke event handlers asynchronously via the event loop, dispatchEvent() invokes event handlers synchronously. All applicable event handlers are called and return before dispatchEvent() returns.
dispatchEvent(event)
Parameter | event | The Event object to dispatch. Its Event.target property will be set to the current EventTarget. |
---|---|---|
Returns | Boolean | false if event is cancelable, and at least one of the event handlers which received event called Event.preventDefault(). Otherwise true. |
Exceptions | InvalidStateError DomException | Thrown if the event's type was not specified during event initialization. |
Event Types
Events are fired inside the browser window, and tend to be attached to a specific item that resides in it. This might be a single element, a set of elements, the HTML document loaded in the current tab, or the entire browser window. There are many different types of events that can occur.
- Selects - the user selects a certain element.
- Clicks - the user clicks a certain element.
- Hovers - the user hovers the cursor over a certain element.
- Keyboard - the user chooses a key on the keyboard.
- Resize - the user resizes the browser window.
- Closes - the user closes the browser window.
- Loading - a web page finishes loading.
- Form Submission - a form is submitted.
- Video - a video is played, paused, or ends.
- Error - an error occurs.
Event Type | Description | Fired On |
---|---|---|
Animation | Events related to the Web Animation API. Used to respond to changes in animation status (e.g. when an animation starts or ends). |
Document Window HTMLElement |
Asynchronous | Events related to the asynchronous fetching of data. | AbortSignal XMLHttpRequest FileReader |
Clipboard | Events related to the Clipboard API. Used to notify when content is cut, copied, or pasted. |
Document Element Window |
Composition |
Events related to composition; entering text "indirectly" (rather than using normal keyboard presses). For example, text entered via a speech to text engine, or using special key combinations that modify keyboard presses to represent new characters in another language. |
Element |
CSS Transition | Events related to CSS Transitions. Provides notification events when CSS transitions start, stop, are cancelled, etc. |
Document HTMLElement Window |
Drag & Drop |
Events related to using the HTML Drag and Drop API and wheel events. Drag and Wheel events are derived from mouse events. While they are fired when using mouse wheel or drag/drop, they may also be used with other appropriate hardware. |
Drag events fired on Document Wheel events fired on Document and Element |
Focus | Events related to elements gaining and losing focus. | Element Window |
Form | Events related to forms being constructed, reset and submitted. | HTMLFormElement |
Fullscreen |
Events related to the Fullscreen API. Used to notify when the transitioning between full screen and windowed modes, and also of errors occurring during this transition. |
Document Element |
Inputs | Events related to HTML input elements e.g. <input>, <select>, or <textarea>. | HTMLElement HTMLInputElement |
Keyboard | Events related to using a keyboard. Used to notify when keys are moved up, down, or just pressed. |
Document Element |
Mouse |
Events related to using a computer mouse. Used to notify when the mouse is clicked, doubleclicked, up and down events, right-click, movement in and out of an element, text selection, etc. Pointer events provide a hardware-agnostic alternative to mouse events. Drag and Wheel events are derived from mouse events. |
Element |
Pointer | Events related to the Pointer Events API. Provides hardware-agnostic notification from pointing devices including Mouse, Touch, pen/stylus. |
Document HTMLElement |
Events related to printing. | Window | |
Promise Rejection | Events sent to the global script context when any JavaScript promise is rejected. | Window |
Text Selection | Selection API events related to selecting text. | Event (selectionchange) fired on HTMLTextAreaElement, HTMLInputElement. |
Button Click
// BUTTON CLICK EXAMPLES <button id="btn1Script1" class="btn btn-bs-primary">Run Script 1</button> <a id="btn2Script1" class="btn btn-bs-primary">Run Script 1</a> <input id="btn3Script1" type="button" class="btn btn-bs-primary" value="Run Script 1" />
$("#btn1Script1").click(function(){ alert("Button btn1Script1 Clicked"); }); $("#btn2Script1").click(function(){ alert("Button btn2Script1 Clicked"); }); $("#btn3Script1").click(function(){ alert("Button btn3Script1 Clicked"); });
Run Script 1window.addEventListener("DOMContentLoaded", (event) => { const btn1Script2 = document.getElementById("btn1Script2"); if (btn1Script2) { btn1Script2.addEventListener("click", function() { alert("Button btn1Script2 Clicked"); },false); } else {console.log("Does not exist yet");} });
Standard JS Click Event$('p.target') .css( { background:'#000',color:'#fff',border:'2px solid #000',fontWeight:'900',fontSize:'1.5rem' } ) .click(function() { $(this) .css( 'background','#aaf' ) .animate( { width:'300px', borderWidth:'30px',marginLeft:'100px' }, 2000, function(){ $(this).fadeOut(); } ); });
Click on the following div and watch it animate and disappear
Click On Me
window.addEventListener("DOMContentLoaded", (event) => { ... const btn1Script3 = document.getElementById("btn1Script3"); if (btn1Script3) { btn1Script3.addEventListener("click", function() { const results1 = document.getElementById("results1"); const rndCol = `rgb(${random(255)}, ${random(255)}, ${random(255)})`; results1.style.backgroundColor = rndCol; },false); } else {console.log("Does not exist yet");} });
Focus
window.addEventListener("DOMContentLoaded", (event) => { ... const txtIn1 = document.getElementById("txtIn1"); ... if (txtIn1) { txtIn1.addEventListener("focus", function(event) { event.target.style.background = "pink"; }); txtIn1.addEventListener("blur", (event) => { event.target.style.background = ""; }); } if (btnIn1) { btnIn1.addEventListener("focus", function(event) { event.target.style.background = "pink"; }); btnIn1.addEventListener("blur", (event) => { event.target.style.background = ""; }); } });
Event Type ------------------------------------------------------------------ Clipboard Document, Element, Window Drag & Drop Document, Element Focus Element, Window Form HTMLFormElement Inputs HTMLElement, HTMLInputElement Keyboard Document, Element Mouse Element Pointer Document, HTMLElement Text Selection Event (selectionchange) fired on: HTMLTextAreaElement, HTMLInputElement
Mouse Event
The MouseEvent interface represents events that occur due to the user interacting with a pointing device (such as a mouse). Common events using this interface include click, dblclick, mouseup, mousedown.
MouseEvent derives from UIEvent, which in turn derives from Event. Though the MouseEvent.initMouseEvent() method is kept for backward compatibility, creating of a MouseEvent object should be done using the MouseEvent() constructor.
Several more specific events are based on MouseEvent, including WheelEvent, DragEvent, and PointerEvent.
Event <--- UIEvent <--- MouseEvent
Constructor
MouseEvent() | Creates a MouseEvent object. |
---|
Instance Properties
This interface also inherits properties of its parents, UIEvent and Event.
Property | Description |
---|---|
MouseEvent.altKey | Returns true if the alt key was down when the mouse event was fired. Read only |
MouseEvent.button | The button number that was pressed (if applicable) when the mouse event was fired. Read only |
MouseEvent.buttons | The buttons being pressed (if any) when the mouse event was fired. Read only |
MouseEvent.clientX | The X coordinate of the mouse pointer in local (DOM content) coordinates. Read only |
MouseEvent.clientY | The Y coordinate of the mouse pointer in local (DOM content) coordinates. Read only |
MouseEvent.ctrlKey | Returns true if the control key was down when the mouse event was fired. Read only |
MouseEvent.metaKey | Returns true if the meta key was down when the mouse event was fired. Read only |
MouseEvent.movementX | The X coordinate of the mouse pointer relative to the position of the last mousemove event. Read only |
MouseEvent.movementY | The Y coordinate of the mouse pointer relative to the position of the last mousemove event. Read only |
MouseEvent.offsetX | The X coordinate of the mouse pointer relative to the position of the padding edge of the target node. Read only |
MouseEvent.offsetY | The Y coordinate of the mouse pointer relative to the position of the padding edge of the target node. Read only |
MouseEvent.pageX | The X coordinate of the mouse pointer relative to the whole document. Read only |
MouseEvent.pageY | The Y coordinate of the mouse pointer relative to the whole document. Read only |
MouseEvent.relatedTarget | The secondary target for the event, if there is one. Read only |
MouseEvent.screenX | The X coordinate of the mouse pointer in global (screen) coordinates. Read only |
MouseEvent.screenY | The Y coordinate of the mouse pointer in global (screen) coordinates. Read only |
MouseEvent.shiftKey | Returns true if the shift key was down when the mouse event was fired. Read only |
MouseEvent.x | Alias for MouseEvent.clientX. Read only |
MouseEvent.y | Alias for MouseEvent.clientY. Read only |
Examples
altKey Property
<p>Click anywhere to test the <code>altKey</code> property.</p> <p id="log"></p>
let log = document.querySelector("#log"); document.addEventListener("click", logKey); function logKey(e) { log.textContent = `The alt key is pressed: ${e.altKey}`; }
altKey
Mouse Button
<button id="button" oncontextmenu="event.preventDefault();">Click Here</button> <p id="log"></p>
let button = document.querySelector("#button"); button.addEventListener("mouseup", (e) => { let log = document.querySelector("#log"); switch (e.button) { case 0: log.textContent = "Left button clicked."; break; case 1: log.textContent = "Middle button clicked."; break; case 2: log.textContent = "Right button clicked."; break; default: log.textContent = `Unknown button code: ${e.button}`; } });
Click HereResponse
Mouse Position
<p>Move your mouse to see its position.</p> <p id="screen-log"></p>
let screenLog = document.querySelector("#screen-log"); document.addEventListener("mousemove", logKey); function logKey(e) { screenLog.innerText = ` Screen X/Y: ${e.screenX}, ${e.screenY} Client X/Y: ${e.clientX}, ${e.clientY}`; }
Response
Move your mouse to see its position.
Mouse Position Click
Response
Click your mouse to see its position.
Link Position Click
In my Music Tabs application, there is a need to be able to set chords into positions on the page. The page is a set number of fixed characters wide, the default is 77 characters. The interface dialog for adding chords should pop up somewhere near the link. The problem here is to figure out where the mouse is when it clicks on the position link. In addition to needing to know the mouse position, we also need to know the line number and the character position. If we didn't need the mouse position, this would be easy. Normally the way to get the mouse position or any other mouse related information, it would be done by assigning a click event function. Because there are many positions, i.e. many links, that idea won't work. We could make the event trigger be a class instead of an id, but then we run into the problem of how to get the other data.
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
Response
Click on link to see its position.
Example: Mouse Position
Example: Simulating A Mouse Click
This example demonstrates simulating a click (programmatically generating a click event) on a checkbox using DOM methods. Event state (canceled or not) is then determined with the return value of method EventTarget.dispatchEvent().
<p> <label><input type="checkbox" id="checkbox" /> Checked</label> </p> <p> <button id="button">Click me to send a MouseEvent to the checkbox</button> </p>
function simulateClick() { // GET THE ELEMENT TO SEND A CLICK EVENT const cb = document.getElementById("checkbox"); // CREATE A SYNTHETIC CLICK MouseEvent let evt = new MouseEvent("click", { bubbles: true, cancelable: true, view: window, }); // SEND THE EVENT TO THE CHECKBOX ELEMENT cb.dispatchEvent(evt); } document.getElementById("button").addEventListener("click", simulateClick);
Parameter | Description |
---|---|
Returns:
Run Script 2