In this example, the focus trap is activated when the element is rendered.
We also pass a function to onDeactivate
to allow Escape
key to deactivate
the focus trap.
<div class="mb-4">
<button type="button" {{on "click" this.activate}} class="button">
Activate trap
</button>
</div>
{{#if this.isActive}}
<div
class="trap is-active"
{{focus-trap
focusTrapOptions=(hash
onDeactivate=this.deactivate
)
}}
>
<p class="mb-4">
Here is a focus trap
<a href="javascript:void(0)">with</a>
<a href="javascript:void(0)">some</a>
<a href="javascript:void(0)">focusable</a>
parts.
</p>
<button type="button" {{on "click" this.deactivate}} class="button">
Deactivate trap
</button>
</div>
{{/if}}
When this focus trap activates, focus jumps to a specific, manually specified element.
<div class="mb-4">
<button type="button" {{on "click" this.activate}} class="button">
Activate trap
</button>
</div>
<div
class="trap {{if this.isActive "is-active"}}"
tabindex="-1"
{{focus-trap
isActive=this.isActive
shouldSelfFocus=true
focusTrapOptions=(hash
onDeactivate=this.deactivate
clickOutsideDeactivates=true
)
}}
>
<p class="pb-4">
Here is a focus trap
<a href="javascript:void(0)">with</a>
<a href="javascript:void(0)">some</a>
<a href="javascript:void(0)">focusable</a>
parts.
</p>
<button type="button" {{on "click" this.deactivate}} class="button">
Deactivate trap
</button>
</div>
Initial focus is on the containing element, which has tabindex="-1"
; so when you tab through the trap focus does not return to the container.
In this example, clicking outside of the container will deactivate the focus
trap. Note the option clickOutsideDeactivates
.
This example uses the modifier argument shouldSelfFocus
. The same could be
achieved by adding an id
to the container and passing the selector to initialFocus
in focusTrapOptions
. However, shouldSelfFocus
is a short hand for passing
the element directly to focusTrapOptions
.
<div class="mb-4">
<button type="button" {{on "click" this.activate}} class="button">
Activate trap
</button>
</div>
<div
class="trap {{if this.isActive "is-active"}}"
{{focus-trap
isActive=this.isActive
focusTrapOptions=(hash
onDeactivate=this.deactivate
initialFocus="#initial-focusee"
)
}}
>
<p class="pb-4">
Here is a focus trap
<a href="javascript:void(0)">with</a>
<a href="javascript:void(0)">some</a>
<a href="javascript:void(0)">focusable</a>
parts.
<br>
Initially focused input
<input type="text" id="initial-focusee" class="bg-transparent border border-gray-400 dark:border-gray-600">
</p>
<button type="button" {{on "click" this.deactivate}} class="button">
Deactivate trap
</button>
</div>