DOM
Hologram renders your templates into the browser's DOM and keeps it in step with your component state. You describe what the page should show, and Hologram works out what to change. Some of what the DOM holds belongs to the browser rather than to your markup, such as which element has focus. This page covers how Hologram handles that state, so you can control it from your components without writing JavaScript.
Focus
Moving Focus with $focused
The $focused attribute declares whether an element should have focus. Set it from your state, and Hologram moves focus when the value changes:
<button $click="edit_title">Edit title</button>
<input type="text" name="title" $focused={@editing_title?} />
state :editing_title?, :boolean, default: false
def action(:edit_title, _params, component) do
put_state(component, :editing_title?, true)
end
Clicking "Edit title" sets @editing_title? to true, and the title field takes focus.
Like the value and checked attributes of synchronized inputs (see Forms), $focused takes its value from your state. Unlike them, Hologram applies it only when the value changes, as the next section explains.
$focused written without a value means true. It goes on an HTML element: on a component tag it has no effect, the same as an event binding, so pass the value to the component as a prop and set $focused on the element inside it.
When Focus Moves
Hologram moves focus only at these moments:
- An element that appears with
$focusedtrue takes focus. - An element whose
$focusedturns from false to true takes focus. - An element whose
$focusedturns from true to false loses focus, if it still has it.
A re-render that leaves $focused as it was doesn't move focus. Say the title field has focus because @editing_title? is true, and the user clicks into another field. If an action then changes some other part of the state, the page re-renders with @editing_title? still true, but focus stays in the field the user picked. When one render asks for focus on several elements, the first one in document order that can take focus gets it.
On the first page load, the server renders $focused={true} as the HTML autofocus attribute, so the browser focuses the element before Hologram's runtime has started. That happens before any event listener is attached, so it doesn't trigger $focus, and if the user leaves the field before the page has loaded, $blur doesn't fire either.
Only elements that can take focus get it, such as inputs, buttons, links and elements with a tabindex. A disabled or hidden element can't, so Hologram passes over it to the next element that asks. If one render enables an element and sets its $focused to true, it gets focus. If it asks for focus while still disabled, it doesn't get focus later when it's enabled, the same as the browser's autofocus.
Focusing the Same Element Again
Setting the state to the value it already has moves nothing. In the example above, @editing_title? stays true after the first click. If the user then clicks somewhere else and presses "Edit title" again, the value doesn't change, so focus doesn't come back. Clear the state when the user leaves the field, with a $blur handler:
<input type="text" name="title" $focused={@editing_title?} $blur="title_blurred" />
def action(:title_blurred, _params, component) do
put_state(component, :editing_title?, false)
end
Now every click on "Edit title" turns the value from false to true, which moves focus.
Focusing the First Invalid Field
The same pattern works with one state value that names the field to focus. The example below moves focus to the first invalid field after a failed submit:
<form $submit="submit">
<input type="email" name="email" $focused={@focused_field == :email} $blur="field_blurred" />
<input type="password" name="password" $focused={@focused_field == :password} $blur="field_blurred" />
<button type="submit">Sign in</button>
</form>
state :focused_field, :atom, default: nil
def action(:submit, params, component) do
case validate(params.event) do
{:ok, _data} ->
component
{:error, field} ->
put_state(component, :focused_field, field)
end
end
def action(:field_blurred, _params, component) do
put_state(component, :focused_field, nil)
end
Each field clears the state when the user leaves it, so a second failed submit with the same error is a change again and brings focus back.
The autofocus Attribute
The plain HTML autofocus attribute works as well. Browsers apply it only when a page loads. Hologram also applies it when:
- a page is reached by client-side navigation
- an element appears after an action, such as a field in a form that opens
{%if @editing?}
<input type="text" name="title" autofocus />
{/if}
An element takes either autofocus or $focused, not both, and combining them fails the build. If autofocus comes through an attribute spread, $focused wins.
Focus and Navigation
A page reached by client-side navigation is shown before its code has finished loading. Its autofocus or $focused element takes focus as soon as the page appears, so a field the user clicks into while the page loads keeps focus when loading completes. A page that declares no focus starts with nothing focused, like a page loaded in full, so keyboard users continue from the top of the new page. Going back or forward in the browser history works the same way: when the page is shown again, its autofocus or $focused element takes focus, and if it has neither, nothing is focused.
Focus Events
$focus and $blur report focus changes the user makes, and those your own code makes through JavaScript Interop. Focus that Hologram moves to apply $focused or autofocus doesn't trigger them, the same way setting a synchronized input's value doesn't trigger $change: your state already says where focus is. That also keeps a $blur handler that clears the state, like the ones above, from undoing a move from one field to another.
$focus is an event and $focused is state, so a binding like $focus={true} is almost always a typo. A literal true fails the build, and a binding that evaluates to true raises an error when the event fires.
Element Refs
$ref names an element, so other parts of your app can point at it. Code that needs the element itself, like a JavaScript library you hand it to, gets it with JS.element/1:
<canvas $ref="sales_chart"></canvas>
<button $click="draw_chart">Draw chart</button>
def action(:draw_chart, _params, component) do
JS.new(:Chart, [JS.element(:sales_chart), %{type: "bar"}])
component
end
For what Hologram does itself, like moving focus with $focused or setting a drag image with $data_transfer, use that instead of JavaScript.
Naming Elements
A ref is an identifier, the same kind of value channels and $key take. An identifier is an atom, like :search, or a tuple of an atom followed by one or more integers, strings or atoms, like {:message, 42}. None of its atoms can be nil, true or false. A ref that's a single atom is an atom ref, and one that's a tuple is a tuple ref, whose values after the name are its parts. An element ref is never an Elixir reference, the kind make_ref/0 returns. The text form $ref="sales_chart" is the atom :sales_chart, so it takes only a name you can write as an atom without quotes. Write any other ref as an expression. That's also how each element in a loop gets its own:
{%for message <- @messages}
<div $ref={:message, message.id}>{message.text}</div>
{/for}
{:message, 42}
|> JS.element()
|> JS.call(:scrollIntoView, [])
A ref can come from state or props, like $ref={@list_ref}. A value that isn't an identifier raises a Hologram.MisuseError when the element renders.
$ref goes on an HTML element. A component renders no element of its own, so $ref on a component tag fails the build. Put it on an element inside the component and pass the ref as a prop. $ref on <slot>, <window>, <document> or <html> fails the build too.
Refs Are Page-Wide
A ref names one element on the whole page, across components. It's plain data, so passing one to a component passes the value, and keeping one in state is safe:
<MessageList list_ref={:messages} />
Inside MessageList, the element takes the ref from the prop:
<ul $ref={@list_ref}>...</ul>
A reusable component shouldn't name its elements with a fixed ref, since the page may render it twice or use the same name itself. Take the ref as a prop, or build one from something unique to each instance, like its cid, and start it with the package's name:
<ul $ref={:acme_ui_menu, @cid}>...</ul>
:window and :document are built-in refs. JS.element(:window) returns the window and JS.element(:document) the document, so code that takes a ref can be given the window, like scroll_ref={:window}. A template can't name an element :window or :document.
JS.element/1 also takes a native value and returns it unchanged, so a component that takes a ref prop can pass the prop to JS.element/1 whether it was given a ref or an element.
Two elements rendered under one ref raise a Hologram.MisuseError that names the ref and the components that rendered them. Elements in the branches of one {%if} and {%else} don't clash, since only one of them renders. An element that takes another's place under the same ref isn't a duplicate either. The build fails for the mistakes it can see in literal refs:
- the same atom ref on two elements of one template, unless they're in the two branches of one
{%if}and{%else} - an atom ref inside a
{%for}, or in a component that renders itself - a component whose template has an atom ref, rendered twice or inside a
{%for} - the same atom ref in a page, its layout and the components they render together
- a ref name used with different numbers of parts on one page
Keep the Ref, Not the Element
Keep the ref in state and look the element up when you need it. An element kept in state is the one a past render put on the page, and a later render can replace it.
Elements an Action Renders
Hologram renders after an action returns, so an action can't look up an element its own state change adds. Take a reply form that opens with a rich text editor, a JavaScript library that needs the element it runs in:
<button $click="open_reply">Reply</button>
{%if @replying?}
<div $ref="reply_editor"></div>
{/if}
Looking up :reply_editor in the action that sets @replying? raises, since the <div> isn't on the page until that action returns. Look it up in a chained action instead, which runs after that render and before the browser paints:
def action(:open_reply, _params, component) do
component
|> put_state(:replying?, true)
|> put_action(:start_reply_editor)
end
def action(:start_reply_editor, _params, component) do
JS.new(:Editor, [JS.element(:reply_editor)])
component
end
When nothing is rendered under a ref, JS.element/1 raises a Hologram.MisuseError that names the ref. If a template declares the ref, the message says nothing renders it right now and points to a chained action. For a misspelled name, it suggests the closest ref the page declares.
A template renders on the server too, where JS.element/1 returns a placeholder like every JS interop function, and in the browser the element may not exist yet while the template renders. So JS.element/1 in a template fails the build. Pass the ref itself instead.
Changes Made Through JS Interop
Hologram's virtual DOM patching is aware of JS interop. If you manipulate the DOM directly via JS interop (e.g. appending child elements), those changes are preserved across Hologram re-renders, as long as the container element is present in the template:
state :counter, :integer, default: 0
def template do
~HOLO"""
<button $click={:populate}>Populate JS subtree</button>
<button $click={:increment}>Increment counter</button>
<p>Counter: {@counter}</p>
<div id="js_managed"></div>
"""
end
def action(:populate, _params, component) do
~JS"""
const container = document.getElementById('js_managed');
const span = document.createElement('span');
span.textContent = 'JS managed content';
container.appendChild(span);
"""
put_state(component, :counter, component.state.counter + 1)
end
def action(:increment, _params, component) do
put_state(component, :counter, component.state.counter + 1)
end
In this example, clicking "Populate JS subtree" adds a span via JavaScript and increments the counter. Clicking "Increment counter" afterwards will update the counter display without removing the JS-managed span.