Skip to content

Events

Event

  • An event is a signal that something has happened.
  • All DOM nodes generate signals.
  • Events are not limited to DOM

Mouse events

  • click – when the mouse clicks on an element (touchscreen devices generate it on a tap)
  • contextmenu – when the mouse right-clicks on an element.
  • mouseover / mouseout – when the mouse cursor comes over / leaves an element.
  • mousedown / mouseup – when the mouse button is pressed / released over an element.
  • mousemove – when the mouse is moved.

From, keyboard, document and CSS events (just few of them)

  • Form
    • submit – when the visitor submits a <form>
    • focus – when the visitor focuses on an element, e.g. on an <input>
  • Keyboard
    • keydown and keyup – when the visitor presses and then releases the button (keypress - deprecated).
  • Document
    • DOMContentLoaded – when the HTML is loaded and processed, DOM is fully built.
  • CSS
    • transitionend – when a CSS-animation finishes.

All the Element events (from mdn)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
afterscriptexecute Non-standard
animationcancel
animationend
animationiteration
animationstart
auxclick
beforeinput
beforematch Experimental
beforescriptexecute Non-standard
beforexrselect Experimental
blur
click
compositionend
compositionstart
compositionupdate
contentvisibilityautostatechange Experimental
contextmenu
copy
cut
dblclick
DOMActivate Deprecated
DOMMouseScroll Non-standard Deprecated
focus
focusin
focusout
fullscreenchange
fullscreenerror
gesturechange Non-standard
gestureend Non-standard
gesturestart Non-standard
gotpointercapture
input
keydown
keypress Deprecated
keyup
lostpointercapture
mousedown
mouseenter
mouseleave
mousemove
mouseout
mouseover
mouseup
mousewheel Non-standard Deprecated
MozMousePixelScroll Non-standard Deprecated
paste
pointercancel
pointerdown
pointerenter
pointerleave
pointermove
pointerout
pointerover
pointerrawupdate
Experimental
pointerup
scroll
scrollend
securitypolicyviolation
touchcancel
touchend
touchmove
touchstart
transitioncancel
transitionend
transitionrun
transitionstart
webkitmouseforcechanged Non-standard
webkitmouseforcedown Non-standard
webkitmouseforceup Non-standard
webkitmouseforcewillbegin Non-standard
wheel

Docs
- Events, mdn - Events, whatwg - Drag and drop Events, whatwg - Media Events, whatwg

Event handler - 1

To react on events - assign a handler – a function that runs in case of an event.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<input value="Click 1" onclick="alert('Click 1')" type="button">

<script>
    function click2() {
        alert('Click 2');
    }
</script>
<input type="button" onclick="click2()" value="Click 2">

<input id="elem" type="button" value="Click 3">
<script>
    elem.onclick = function() {
        alert('Click 3');
    };
</script>

Event handler - 2

A handler can be set in HTML with an attribute named on<event>.

Assign a handler using a DOM property on<event>.

The handler is always in the DOM property: the HTML-attribute is just one of the ways to initialize it.

As there’s only one onclick property, we can’t assign more than one event handler.

Event handler - 3

Can assign an existing function as a handler directly

To remove a handler – assign elem.onclick = null

1
2
3
4
function sayThanks() {
    alert('Thanks!');
}
elem.onclick = sayThanks;

Event handler - this

Accessing the element: this

The value of this inside a handler is the element.

1
<button onclick="alert(this.innerHTML)">Click 4</button>

addEventListener

  • Previous methods enable only to add single event listener.
    • element.addEventListener(event, handler[, options]);
    • element.removeEventListener(event, handler[, options]);
      • Removal requires the same (by reference) function


  • event – event name, “click”
  • handler – handler function
  • option – object
    • once: if true, then the listener is automatically removed after it triggers.
    • capture: the phase where to handle the event (bubbling and capturing). For historical reasons, options can also be false/true, same as {capture: false/true}.
    • passive: if true, then the handler will not preventDefault()

Event object

  • All events also send detailed info about themselves as parameter to handler

  • Some properties of the event object

    • Event.type – "click"
    • Event.currentTarget – element, that handled the event. (usually same as this)
    • Event.target - element, that triggered the event (originator).
    • Event.clientX / clientY – coordinates of mouse event.

Object handlers: handleEvent

Assign an object as an event handler using addEventListener

When an event occurs, objects handleEvent method is called.

Bubbling, capturing

DOM Tree

When an event happens on an element, it first runs the handlers on it, then on its parent, then all the way up on other ancestors.

  • Almost all events bubble
    • focus does not bubble
    • ..and some more

event.target

  • The most deeply nested element that caused the event is called a target element, accessible as event.target.
  • event.target – is the “target” element that initiated the event, it doesn’t change through the bubbling process.
  • this – is the “current” element, the one that has a currently running handler on it (=event.currentTarget).

Stopping bubbling

Bubbling goes upwards till <html>, and then to document object, and some events even reach window, calling all handlers on the path.

Any handler may decide that the event has been fully processed and stop the bubbling. event.stopPropagation()

If an element has multiple event handlers on a single event, then even if one of them stops the bubbling, the other ones still execute.

To stop the bubbling and prevent handlers on the current element from running - event.stopImmediatePropagation()

Capturing

Capturing phase – the event goes down to the element.

Target phase – the event reached the target element.

Bubbling phase – the event bubbles up from the element.

elem.addEventListener(..., {capture: true})

Browser default actions

  • Many events automatically lead to certain actions performed by the browser.


  • A click on a link – initiates navigation to its URL.
  • A click on a form submit button – initiates its submission to the server.
  • Pressing a mouse button over a text and moving it – selects the text.

Preventing default actions

  • Preventing browser default actions

    • The main way is to use the event object. There’s a method event.preventDefault().
    • If the handler is assigned using on<event> (not by addEventListener), then returning false also works the same.
  • Certain events flow one into another. If first event is prevented, there will be no second. (mouse click -> element focus)

  • The property event.defaultPrevented is true if the default action was prevented, and false otherwise.

Custom events

  • The generic Event(name, options) constructor accepts an arbitrary event name and the options object with two properties:
    • bubbles: true if the event should bubble.
    • cancelable: true if the event.preventDefault() should work.
  • Other constructors of native events like MouseEvent, KeyboardEvent and so on accept properties specific to that event type.
  • For custom events we should use CustomEvent constructor. It has an additional option named detail, assign the event-specific data to it. Handlers can access it as event.detail.
  • After an event object is created, “run” it on an element using the call elem.dispatchEvent(event).
1
2
3
4
5
const dogFound = new CustomEvent("animalfound", {
    detail: {
        name: "dog",
    },
});

Forms

  • document.forms - A form is available as document.forms[name/index].
  • form.elements - Form elements are available as form.elements[name/index], or can use just form[name/index]. The elements property also works for <fieldset>.
  • element.form - Elements reference their form in the form property.
  • Value is available as input.value, textarea.value, select.value etc, or input.checked for checkboxes and radio buttons.
  • For <select> we can also get the value by the index select.selectedIndex or through the options collection select.options.

https://html.spec.whatwg.org/multipage/forms.html.

Focus/Blur

  • An element receives a focus when the user either clicks on it or uses the Tab key on the keyboard
  • The moment of losing the focus - “blur”
  • Event handlers – onfocus, onblur

Methods elem.focus() and elem.blur() set/unset the focus on the element.

tabindex

  • Many elements do not support focusing. Focus/blur support is guaranteed for elements that a visitor can interact with: <button>, <input>, <select>, <a>
  • This can be changed using HTML-attribute tabindex.
  • The tab switch order is: elements with tabindex from 1 and above go first (in the tabindex order), and then elements without tabindex (e.g. a regular <input>). tabindex="0" puts an element among those without tabindex. That is, when we switch elements, elements with tabindex=0 go after elements with tabindex ≥ 1.
  • Usually it’s used to make an element focusable, but keep the default switching order. tabindex="-1" allows only programmatic focusing on an element. - The Tab key ignores such elements, but method elem.focus() works.

(Not) Bubbling of Focus/Blur

Events focus and blur do not bubble.

There are focusin and focusout events – exactly the same as focus/blur, but they bubble. They must be assigned using elem.addEventListener, not on<event>.

The current focused element is available as document.activeElement.

Events: change, input, cut, copy, paste

  • change – a value was changed
    • For text inputs triggers on focus loss.
  • input - for text inputs on every change.
    • Triggers immediately unlike change.
  • cut/copy/paste
    • The action can be prevented. The event.clipboardData property gives read/write access to the clipboard.

Forms: event and method submit

The submit event triggers when the form is submitted, it is usually used to validate the form before sending it to the server or to abort the submission and process it in JavaScript.

The method form.submit() allows to initiate form sending from JavaScript. We can use it to dynamically create and send our own forms to server. submit event is not generated

Page: DOMContentLoaded, load, beforeunload, unload

  • The lifecycle of an HTML page has three important events:
    • DOMContentLoaded – the browser fully loaded HTML, and the DOM tree is built, but external resources like pictures <img> and stylesheets may be not yet loaded.
    • load – not only HTML is loaded, but also all the external resources: images, styles etc.
    • beforeunload/unload – the user is leaving the page.

Resource loading: onload and onerror

  • Browser allows to track the loading of external resources – scripts, iframes, pictures and so on.
    • onload – successful load,
    • onerror – an error occurred.

Basically for any resource that has an external src.