I\'m writing a custom web component that is meant to be interactive. How can I tell the browser that this custom component should receive focus?
I wish that my custom el
Based on this demo that I found in this question, I have this answer:
Just add the tabindex
attribute to the elements you want to be focusable.
// Add this to createdCallback function:
if (!this.hasAttribute('tabindex')) {
// Choose one of the following lines (but not both):
this.setAttribute('tabindex', 0);
this.tabIndex = 0;
}
// The browser automatically syncs tabindex attribute with .tabIndex property.
Clicking on the element will give it focus. Pressing tab will work. Using :focus
in CSS will also work. keydown
and keyup
events work, although keypress
doesn't (but it's deprecated anyway). Tested on Chrome 44 and Firefox 40.
Also note that this.tabIndex
returns -1
even if the HTML attribute is missing, but this has a different behavior than setting tabindex="1"
:
: No tabindex
attribute, the element is not focusable.
: The element is not reachable through tab-navigation, but it is still focusable by clicking.References: