Event Listener
Adding an Event Listener
image.addEventListener('load', function(e) { newPhotoIsDoneLoading(e); }, false);
document.ontouchstart = function(e){ }
element.onclick.addListener((event) => {})
element.onclick = function () {}
window.onload = function () {}
Adding an Event Listener from HTML
<body onload="load();"></body>
Removing an Event Listener
window.removeEventListener("keydown", handlerFunction);
Prevent default event handling
- prevent "Submit" button from submitting a form, or
- prevent a link from following the URL,
- prevent from scrolling
event.preventDefault();
Check whether event can actually be cancelled
if (event.cancelable) {
event.preventDefault();
}
Event Propagation
const grandparent = document.querySelector(".grandparent")
const parent = document.querySelector(".parent")
const child = document.querySelector(".child")
Capture Phase
- Document
- Grandparent
- Parent
- Child Bubble Phase
- Child
- Parent
- Grandparent
- Document
Capture
grandparent.addEventListener("click",
e => {
// ...
},
{ capture: true }
)
Stop Event Propagation
grandparent.addEventListener("click",
e => {
e.stopPropagation()
},
{ capture: true }
)
One-time event listener
grandparent.addEventListener("click",
e => {
// ...
},
{ once: true }
)
Stop Event Propagation
- prevent further propagation of an event through the DOM (offspring -> ancestors)
event.stopPropagation();
Target DOM Element
var target = event.target;
console.log(target.classname);
Load Events
DOMContentLoaded
– after DOM is loaded (before img
and CSS)
document.addEventListener("DOMContentLoaded", function(){
//....
});
load
– after everything is loaded and parsed
window.addEventListener("load", function(){
// ....
});
Page show and hide
window.addEventListener("pageshow", () => { });
window.addEventListener("pagehide", () => { });
List of user input events
Mouse
mousemove
mouseover
mouseout
mouseenter
mouseleave
mousedown
mouseup
click
mousewheel
Touch
touchstart
touchmove
touchend
touchcancel
touchforcechange
Pointer
pointermove
pointerdown
pointerup
pointerover
pointerout
pointerenter
pointerleave
Gesture
gesturestart
gesturechange
gestureend
Device
devicemotion
deviceorientation
orientationchange
Keyboard
keydown
keypup
keypress
Mouse
section.addEventListener("mousedown", function(e) { handleTouchEnd(e); }, false);
section.addEventListener("mouseup", function(e) { handleTouchStart(e); }, false);
Touch
window.addEventListener("touchstart", function(e){ handleTouchEvent(e); })
function handleTouchEvent(e) {
var touchXAxis = e.target.pageX;
}
section.addEventListener("touchstart", function(e) { handleTouchStart(e); }, false);
section.addEventListener("touchmove", function(e) { handleTouchMove(e); }, false);
section.addEventListener("touchend", function(e) { handleTouchEnd(e); }, false);
Pointer Events
canvas.addEventListener("pointerdown", startPointer)
canvas.addEventListener("pointermove", movingPointer)
canvas.addEventListener("pointerup", endPointer)
function startPointer(e) {
}
function endPointer(e) {
}
function movingPointer(e) {
const coords = {
client: { x: e.clientX, y: e.clientY },
offset: { x: e.offsetX, y: e.offsetY },
page: { x: e.pageX, y: e.pageY },
screen: { x: e.screenX, y: e.screenY },
movement: { x: e.movementX, y: e.movementY },
e: { x: e.x, y: e.y },
}
console.table(coords)
console.log(e.pressure, e.webkitForce)
console.log(e.altitudeAngle, "", e.azimuthAngle, e.tiltX, e.tiltY)
}
Keyboard
window.addEventListener("keydown", function(e){ handleKeyboardEvent(e); })
window.addEventListener("keypress", function(e){ handleKeyboardEvent(e); })
function handleKeyboardEvent(e) {
if (e.keyCode === 39) {
// ...
}
Event
function eventHandler(e) {
console.log(e) // this is the event object
}
Prevent default
document.ontouchstart = function(e){
e.preventDefault();
}
Stop Propagation
document.addEventListener("click", function(e){
e.stopPropagation();
}
Event Target
e.target.parentNode.className
Position – Mouse Down Event
Offset - distance to top left corner of the element clicked on
e.offsetX
e.offsetY
Page
e.pageX
e.pageY
Layer
e.layerX
e.layerY
Client
e.clientX
e.clientY
Screen
e.screenX
e.screenY
List of Events
TouchEvent
touchstart
touchmove
touchcancel
touchend
MouseEvent
mouseenter
mouseleave
mousemove
mouseover
mouseout
-
mousedown
mouseup
click
dblclick
contextmenu
(right click)
KeyboardEvent
keydown
keyup
keypress
DragEvent
drag
dragend
dragenter
dragleave
dragover
dragstart
drop
WheelEvent
wheel
FocusEvent
focusin
focusout
focus
blur
ClipboardEvent
cut
copy
paste
Event Properties and Methods
Event
preventDefault()
stopPropagation()
stopImmediatePropagation()
target
timeStamp
MouseEvent
clientX // horizontal coordinate relative to the current window, when event was triggered
clientY
MovementX // horizontal coordinate relative to the position of the last mousemove event
MovementY
offsetX // horizontal coordinate relative to the position of the edge of the target element
offsetY
pageX // horizontal coordinate elative to the document, when event was triggered
pageY
screenX // horizontal coordinate relative to the screen, when event was triggered
screenY
Touch Event
clientX // horizontal coordinate relative to the current window
clientY
touches // list of all touch objects on the surface
targetTouches // list of all the touch objects that are in contact with the surface and where the touchstart event occured on the same target element as the current target element
changedTouches // list of all the touch objects whose state changed since the previous touch
KeyboardEvent
code //
key // key value
keyCode // Unicode character code of the key
repeat
Keyboard Codes
code | key |
---|---|
65 |
a |
68 |
d |
75 |
k |
73 |
i |
78 |
n |
80 |
p |
82 |
r |
83 |
s |
86 |
v |
ClipboardData
clipboardData
WheelEvent
deltaX
deltaX
deltaX
deltaMode // pixels, lines or pages
Custom Event
const element = document.querySelector(".element");
Sender
element.dispatchEvent(new CustomEvent("somethingchanged", { detail: this.value }));
element.dispatchEvent(new CustomEvent("somethingchanged", { bubbles: true, cancelable: true, detail: this.value }));
Receiver
element.addEventListener("somethingchanged", (e) => console.log(e.detail));
element.addEventListener("somethingchanged", ({ detail }) => console.log(detail));
Simulate event
function simulateClick() {
const event = new MouseEvent("click", {
view: window,
bubbles: true,
cancelable: true,
});
const cb = document.getElementById("checkbox");
const cancelled = !cb.dispatchEvent(event);
if (cancelled) {
console.log("cancelled: A handler called preventDefault.");
} else {
console.log("not cancelled: None of the handlers called preventDefault.");
}
}