Published
Edited
May 10, 2022
8 stars
Insert cell
Insert cell
viewof count = Inputs.button("Add one")
Insert cell
count
Insert cell
Insert cell
{
const node = htl.html`<strong style=${{opacity: Math.min(count, 1)}}>Clicked!</strong>`;
d3.select(node).transition().duration(1000).style("opacity", 0);
return node;
}
Insert cell
Insert cell
<button onclick=${() => mutable time = new Date().toLocaleTimeString("en-US")}>Set time</button>
Insert cell
mutable time = null
Insert cell
Insert cell
viewof state = stateButton("Kick the ball")
Insert cell
state
Insert cell
Insert cell
{
let x = 10;
while (true) {
yield htl.svg`<svg width=${width} height="20">
<circle cx=${x} cy="10" r="9" stroke="black" fill=${state.hovering ? "black" : "none"}></circle>
</svg>`
if (state.clicking) x++;
}
}
Insert cell
Insert cell
viewof state2 = stateButton("Click me")
Insert cell
mutable hasBeenClicked = false
Insert cell
{
if (state2.clicking) mutable hasBeenClicked = true;
}
Insert cell
Insert cell
viewof state3 = stateButton("Kick the ball")
Insert cell
mutable x = 10;
Insert cell
{
while (true) {
if (state3.clicking) mutable x = (mutable x + 1) % width;
yield undefined;
}
}
Insert cell
<svg width=${width} height="20">
<circle cx=${x} cy="10" r="9" stroke="black" fill=${state3.hovering ? "black" : "none"}></circle>
</svg>
Insert cell
Insert cell
colors = ["red", "green", "blue"]
Insert cell
viewof color = Inputs.button("Change color", {
value: colors[0],
reduce: (d) => colors[(colors.indexOf(d) + 1) % colors.length]
})
Insert cell
color
Insert cell
Insert cell
viewof x2 = Inputs.button("Kick the ball", {
value: 10,
reduce: (d) => (d + 10) % width
})
Insert cell
<svg width=${width} height="20">
<circle cx=${x2} cy="10" r="9" stroke="black" fill="none"></circle>
</svg>
Insert cell
Insert cell
stateButton = (label) => {
const node = htl.html`<div><button>${label}</button></div>`;
const button = node.querySelector("button");
const state = { hovering: false, clicking: false };
set(node, state);
button.addEventListener("pointerdown", setState({clicking: true}));
button.addEventListener("pointerup", setState({clicking: false}));
button.addEventListener("mouseenter", setState({hovering: true}));
button.addEventListener("mouseleave", setState({hovering: false, clicking: false}));

function setState(newState) {
return function() {
Object.assign(state, newState);
set(node, state);
}
}
return node;
}
Insert cell
function set(input, value) {
input.value = value;
input.dispatchEvent(new Event("input", {bubbles: true}));
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more