C&C Docs
Log in
Code

Browser code — init()

A page's init() runs once, in the browser, when the page comes alive; the server never runs it. It is where a page does what only a browser can: start a timer, read navigator, wire up an API a directive can't express. Its this is the page: its state, its handlers, its $-methods. This page's own init() drives the clock.

// blocks/browser-code.mjs
export default {
  now: '—',

  init() {
  const pad = (n) => String(n).padStart(2, '0')
  const tick = () => {
    const d = new Date()
    this.now = pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds())
  }
  tick()
  const id = setInterval(tick, 1000)
  // A returned function runs when the page goes away.
  return () => clearInterval(id)
}
}
—

Updated once a second by setInterval inside init().

To reach one element, tag it with x-ref and use $refs from init() or any handler: focus a field, read its .value, measure it.

x-ref → $refs.email.focus() / .value
<div x-data="{ read: '' }" class="space-y-3">
  <input
    x-ref="email"
    type="email"
    placeholder="you@example.com"
    class=""
  />
  <div class="flex gap-2">
    <button @click="$refs.email.focus()" class="">Focus the field</button>
    <button @click="read = $refs.email.value" class="">Read value</button>
  </div>
  <p class="text-sm text-neutral-400">
    Last read via <code class="font-mono">$refs.email.value</code>:
    <span class="" x-text="read || '—'"></span>
  </p>
</div>
Result

Last read via $refs.email.value: —