Alpine.js: The Photography Studio Analogy

Explore $el, $refs, and $root through an interactive photography studio.

Studio Activity Log

Log is empty. Click a button to see actions.

$el

Analogy: The Current Shot. Actions using $el affect the element that triggered the action, like applying a unique filter to a single photograph as you take it.

Interactive Demo:

Click a button to apply an effect directly to that specific "shot".

Effect on active shot:

Code Example:

<button @click="$el.classList.add('active')">
  Activate Me
</button>

$refs

Analogy: Named Lighting. Use $refs to target and control specific, named elements from anywhere within the component, like a remote control for your studio lights.

Interactive Demo:

Lighting Control Panel
Key
Fill
Rim

Code Example:

<div x-ref="myElement"></div>

<button @click="$refs.myElement.focus()">
  Focus Element
</button>

$root

Analogy: The Entire Setup. The $root magic variable refers to the component's top-level element. Use it for actions that affect the entire scene, like turning on the main power or changing the backdrop.

Interactive Demo:

These controls affect the container of all three demos.

Change Backdrop:

Code Example:

<div x-data="{...}">
  <!-- $root refers to this div -->
  <button @click="$root.style.display = 'none'">
    Hide Everything
  </button>
</div>