<p>The lightbulb is <span id="lightbulb">lit</span></p>

<button id="turn-on">Turn on</button>
<button id="turn-off">Turn off</button>
<button id="break">Break</button>
const lightbulb = document.getElementById("lightbulb")

const turnBulbOn = document.getElementById("turn-on")
const turnBulbOff = document.getElementById("turn-off")
const breakBulb = document.getElementById("break")

const machine = {
  initial: "lit",
  states: {
    lit: {
      on: {
        OFF: "unlit",
        BREAK: "broken",
      },
    },
    unlit: {
      on: {
        ON: "lit",
        BREAK: "broken",
      },
    },
    broken: {},
  },
}

const transition = (state, event) => {
  const nextState = machine.states[state]?.on?.[event]
  return nextState || state
}

let state = machine.initial

const send = (event) => {
  state = transition(state, event)
}

turnBulbOn.addEventListener("click", () => {
  send("ON")
  lightbulb.innerText = state
})

turnBulbOff.addEventListener("click", () => {
  send("OFF")
  lightbulb.innerText = state
})

breakBulb.addEventListener("click", () => {
  send("BREAK")
  lightbulb.innerText = state
})

Run Pen

External CSS

  1. https://cdn.jsdelivr.net/npm/water.css@2/out/dark.css

External JavaScript

This Pen doesn't use any external JavaScript resources.