javascripthtmlfocusaccess-keys

highlight text input upon accesskey


I have an HTML page with a text input field for a search string. I would like to give focus to the field when the user hits a predefined key (like META-S).

A similar behaviour is possible for anchors in HTML 5:

<a href="https://www.w3schools.com/css3" accesskey="c">CSS3</a>

I am wondering if there is a more specific solution than to have a JS function listening to all key presses and filtering for the correct one.


Solution

  • You should already be using <label /> for all your form inputs (for accessibility purposes) .. <label /> can have the accesskey attribute.

    Example:

    <label for="search" accesskey="s">Search:</label><br />
    <input type="text" id="search" width="100" />