Events
Events
Events
are things that happen in the system you are programming, which the system tells you about so your code can react to them.
Events are fired to notify code of "interesting changes" that may affect code execution.
const btn = document.querySelector("button"); function random(number) { return Math.floor(Math.random() * (number + 1)); } function setNewRgbColor() { const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`; document.body.style.backgroundColor = rndCol; } // adding listener btn.addEventListener("click", setNewRgbColor); // removing listener btn.removeEventListener("click", setNewRgbColor);
Mutliple handlers
myElement.addEventListener("click", functionA); myElement.addEventListener("click", functionB);
EventTarget
EventTarget
interface is implemented by objects that can receive events and may have listeners for them.
Any target of events implement three methods associated with this interface:
addEventListener()
removeEventListener()
dispatchEvent()
addEventListener()
Sets up a function that will be called when a specified event is delivered to the target.
targets
Common targets are:
- Element (or its children)
- Document and Window
- other objects that support events
Event Types
Mouse Events
- e.g. click, dblclick, mousedown, mouseup, mouseover, mousemove
Keyboard Events
- e.g. keydown, keyup, keypress
Form Events
- e.g. submit, change, focus, blur, input
Touch Events
- e.g. touchstart, touchmove, touchend
Window Events
- e.g. load, resize, scroll, unload
Clipboard Events
- e.g. copy, cut, paste
Drag & Drop Events
- e.g. drag, dragstart, dragend, drop