Search code examples
htmlweb-component

How to make a custom web component focusable?


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 element…

  • could be focused (by tab-navigation);
  • could receive keypresses when focused;
  • could be matched by :focus pseudo-selector.

I'm not using any external library, just plain HTML5 APIs.


Solution

  • 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":

    • <foo></foo>: No tabindex attribute, the element is not focusable.
    • <foo tabindex="-1"></foo>: The element is not reachable through tab-navigation, but it is still focusable by clicking.

    References: