# ally.element.focus
Shifts focus to an element if it does not already have focus.
# Description
The Element.focus()
method is available on all HTMLElement
. Considering the following HTML, applying focus()
to the <span>
element does not do anything. ally.element.focus()
can use ally.get.focusTarget
to identify the nearest focusable ancestor, in this case the <a>
, and shifts focus to that.
<a href="#victim">
<span>click me</span>
</a>
# Focusing in SVG
While focus()
is available on HTMLElement
, this is not necessarily true for SVGElement
. Only Blink and WebKit expose the focus()
method on SVG elements, Gecko, Trident and Edge do not. This will likely change once SVG 2 is a thing. Until then ally.element.focus()
tries to apply HTMLElement.prototoype.focus
to SVGElement
s. This only works for Internet Explorer 9 - 11 and Edge 12, as Gecko and Edge actively prevent this.
In Edge 13 and newer versions ally.element.focus()
injects a <foreignObject>
containing an <input>
element into the SVG element requested to shift focus to. The <input>
is focused and immediately disabled. Since Trident and Edge shift focus to the next focusable ancestor (see Mutating the active element), focus is shifted to the requested SVG element and the injected <foreignObject>
is removed from DOM.
# Focusing in Animated UI
Browsers scroll the focused element into view, if it isn't already. However, this may interfere with widgets revealing content in an animated fashion. As there is no way to focus an element without the browser scrolling the element into view, ally.element.focus()
provides the option undoScrolling
to revert all scroll containers of the focused element to their state before the element got focus.
# Usage
var element = document.getElementById('victim');
var result = ally.element.focus(element);
# Arguments
Name | Type | Default | Description |
---|---|---|---|
element | <selector> |
required | The Element to focus. First element of the collections is used. |
options | <focus options> |
{defaultToAncestor: true} |
The Element to test. |
# Focus options argument
Name | Type | Default | Description |
---|---|---|---|
defaultToAncestor | boolean | false |
If the Element itself is not focusable the first focusable element in its ancestry is used instead. |
undoScrolling | boolean | false |
Revert the browser's native scrollIntoView upon focus behavior. |
# Returns
HTMLElement
that received focus or null
if focus could not be shifted.
# Throws
TypeError
if element
argument does not resolve to an HTMLElement
.
# Changes
# Notes
Cannot focus SVG and MathML elements in Mozilla Firefox and other Gecko based browsers.
# Related resources
ally.element.blur
shifts focus away from an element if it currently has focus.- Managing focus in animated UI