What are events?
Code that is executed non-linearly when something happens
Code that is executed non-linearly when something happens
<button>Click me</button>
let button = document.querySelector("button");
button.addEventListener("click", function handler(event) {
event.target.textContent = "Thank you π";
});
element.addEventListener
, where element is a reference to your element in the DOM tree.this
in that function will refer to the element that you attached the event to.error
, load
, unload
, β¦online
, offline
message
, close
<button id=button>Click me</button>
button.addEventListener("click", evt => {
evt.target.textContent += "π";
});
button.addEventListener("click", evt => {
evt.target.textContent += "β
";
});
<button id=button>Click me</button>
button.onclick = evt => {
evt.target.textContent += "π";
};
button.onclick = evt => {
evt.target.textContent += "β
";
};
button.addEventListener("button", function(event) {
console.log(this);
});
<!DOCTYPE html>
<title>Event caveats</title>
<meta charset="UTF-8"/>
<button>Click me</button>
<script>
let button = document.querySelector("button");
button.addEventListener("click", evt => {
evt.target.textContent = "Thanks π";
});
</script>
<!DOCTYPE html>
<title>Event caveats</title>
<meta charset="UTF-8"/>
<script>
let button = document.querySelector("button");
button.addEventListener("click", evt => {
evt.target.textContent = "Thanks π";
});
</script>
<button>Click me</button>
<!DOCTYPE html>
<title>Event caveats</title>
<meta charset="UTF-8"/>
<script>
document.addEventListener("DOMContentLoaded", () => {
let button = document.querySelector("button");
button.addEventListener("click", evt => {
evt.target.textContent = "Thanks π";
});
});
</script>
<button>Click me</button>
let handler = evt => evt.target.textContent = "π";
button.addEventListener("click", handler);
button.removeEventListener("click", handler);
<button id=button>Click me</button>
button.addEventListener("click", evt => {
evt.target.textContent = "π©"
});
button.removeEventListener("click", evt => {
evt.target.textContent = "π©"
});
Javascript | CSS | Result |
---|---|---|
|
||
|
|
|
|
document.addEventListener("mousemove", evt => {
let x = 100 * evt.x / innerWidth;
let y = 100 * evt.y / innerHeight;
document.body.style.backgroundImage = `radial-gradient(
at ${x}% ${y}%,
black,
transparent
)`;
});
body {
background-image: radial-gradient(
at calc(var(--mouse-x, .5) * 100%)
calc(var(--mouse-y, .5) * 100%),
transparent, black
);
}
document.addEventListener("mousemove", evt => {
let x = evt.x / innerWidth;
let y = evt.y / innerHeight;
let root = document.documentElement;
root.style.setProperty("--mouse-x", x);
root.style.setProperty("--mouse-y", y);
});
"10px"
or "50%"
Input Event | Javascript event |
---|---|
Key pressed or released | keydown , keyup |
Mouse moved | mousemove |
Mouse button pressed or released | mousedown , mouseup |
Input Event | Javascript event |
---|---|
Clicking | click |
Double-clicking | dblclick |
Character held down | keypress |
Form element value changed | input |
Entering or exiting an objectβs bounding box | mouseenter , mouseleave |
<button id=button1>Button 1</button>
<button id=button2>Button 2</button>
let handler = evt => {
evt.target.textContent += "β
";
};
button1.addEventListener("click", handler);
button2.addEventListener("mousedown", evt => {
evt.target.addEventListener(
"mouseup",
handler,
{once: true}
);
});
<textarea id=tweet></textarea>
<span id="output"></span>
tweet.addEventListener("input", evt => {
output.textContent = evt.target.value.length;
});
document.addEventListener("mousemove", evt => {
document.body.textContent = `${evt.x} ${evt.y}`;
});
let start = {x: 0, y: 0};
element.addEventListener("mousedown", evt=> {
start.x = start.x || evt.x;
start.y = start.y || evt.y;
let mousemove = evt => {
evt.target.style.left = (evt.x - start.x) + "px";
evt.target.style.top = (evt.y - start.y) + "px";
};
evt.target.addEventListener("mousemove", mousemove);
evt.target.addEventListener("mouseup", evt => {
evt.target.removeEventListener("mousemove", mousemove);
});
})
{
let start = {x: 0, y: 0};
dragme.addEventListener("mousedown", evt=> {
start.x = start.x || evt.x;
start.y = start.y || evt.y;
let target = evt.target;
let mousemove = evt => {
target.style.left = (evt.x - start.x) + "px";
target.style.top = (evt.y - start.y) + "px";
};
document.addEventListener("mousemove", mousemove);
document.addEventListener("mouseup", evt => {
document.removeEventListener("mousemove", mousemove);
});
});
}
<button id=button>Click <mark>me</mark>!!</button>
button.addEventListener("click", evt => {
evt.target.innerHTML += "π¦";
});
<button>
!If a tree falls in a forest and no one is around to hear it, does it make a sound?
<button id=button>Click <mark>me</mark>!!</button>
button.addEventListener("click", function(evt) {
this.innerHTML += "π¦";
});
this
points to the element the listener was attached to, not the event target
<ol id="palette" class="items">
<template>
<li class="item">
<input type="color">
<button class="delete">π</button>
</li>
</template>
</ol>
<button id="addColor" class="add-item">
Add item
</button>
addColor.addEventListener("click", evt => { let template = palette.querySelector("template"); let item = template.content.cloneNode(true); let del = item.querySelector(".delete"); del.addEventListener("click", e => { e.target.closest(".item").remove(); }); palette.append(item); });
document.addEventListener("click", evt => { if (evt.target.matches(".item .delete")) { evt.target.closest(".item").remove(); } else if (evt.target.matches(".items + .add-item")) { let list = evt.target.previousElementSibling; let template = list.querySelector("template"); let item = template.content.cloneNode(true); list.append(item); } });
<button id=button1>Click <em>me</em>!</button>
<button id=button2>No, click <strong>me</strong>!</button>
<span id=output></span>
let over = evt => output.innerHTML = evt.target.innerHTML;
let out = evt => output.innerHTML = "";
button1.addEventListener("mouseover", over);
button2.addEventListener("mouseover", over);
button1.addEventListener("mouseout", out);
button2.addEventListener("mouseout", out);
focus
(but focusin
does!)blur
(but focusout
does!)mouseenter
(but mouseover
does!)mouseleave
(but mouseout
does!)load
error
element.addEventListener(eventName, evt => {
if (evt.bubbles) {
evt.stopPropagation();
}
})
document
and propagate down to target
element.addEventListener(
eventName,
callback,
{capture: true}
)
Let's write a script that scrolls local links smoothly instead of abruptly jumping to the elements they target!
evt.preventDefault()
Name: <input id=textfield>
textfield.addEventListener("keypress", evt => {
if (evt.key < "A" || evt.key > "Z") {
evt.preventDefault();
}
});
unload
(but beforeunload
can!)input
(but its composite raw events can!)scroll
select
(use user-select: none;
)fullscreenchange
resize
element.addEventListener(eventName, evt => {
if (evt.cancelable) {
evt.preventDefault();
}
})
<input id="name" />
name.addEventListener("input", evt => {
console.log(evt.target.value);
});
name.value = "Lea";
name.addEventListener("input", evt => {
console.log(evt.target.value);
});
name.value = "Lea";
let evt = new InputEvent("input");
name.dispatchEvent(evt);
let evt = new CustomEvent("itemadded", {
detail: {item: item}
});
list.dispatchEvent(evt);
class GithubAPI extends EventTarget {
constructor() {
super();
}
login() {
// ...
let evt = new CustomEvent("login");
this.dispatchEvent(evt);
}
}
let github = new GithubAPI();
github.addEventListener("login", evt => {
// display user info
});