Mouse eventsInline handlersaddEventListenerKeyboard eventsremoveEventListenerCookiesTheme example
01 · MOUSE EVENTS
User acts → event fires → your code runs
1 · the user
Click me
→
2 · the browser
"click"
→
functionhandleClick() {// 3 · your code}
clickpress and release
dblclicktwo quick clicks
mousedownbutton goes down
mouseupbutton is released
02 · INLINE IN HTML
Way 1: onclick in the HTML
<buttononclick="handleClick()">Click me</button><script>functionhandleClick() {alert("The button was clicked");}</script>
With parentheses: the attribute is code that calls the function
Click me
The button was clicked
✓ Quick to write
✗ Mixes HTML with JavaScript
03 · IN JAVASCRIPT
Way 2: addEventListener
let button = document.getElementsByTagName("button")[0];button.addEventListener("click", handleClick);functionhandleClick() {alert("The button was clicked");}
handleClick
You hand over the function. The browser calls it on every click.
handleClick()
Calls it right now, once, and passes its result instead.
04 · KEYBOARD EVENTS
keydown and keyup
A
down: keydownup: keyup
// event log
keydown event.key = "A"
keyup event.key = "A"
keydown event.key = "Enter"
keyup event.key = "Enter"
<inputonkeyup="handleKey(event)">
input.addEventListener("keyup", handleKey);
05 · REMOVING A LISTENER
Make it work only once
button.addEventListener("click", handleClick);functionhandleClick() {alert("Clicked! The listener will be removed"); button.removeEventListener("click", handleClick);}
Click me
Click 1 ✓ runs
Click 2 nothing
listener: attachedlistener: removed
Same event name and the same function, or nothing is removed