Saurabh26
Saurabh26

Reputation: 5

How do I attach an access key to a HTML element

I tried to use accesskey attribute but it requires user to use combinations of keys but I want to use a single key to access the element. I tried to search it on web I couldn't find any thing.

Upvotes: 0

Views: 357

Answers (1)

connexo
connexo

Reputation: 56773

You can do that with the help of Javascript but you really shouldn't as the accesskeys natively available require a modifier for very good reasons.

Please note that this effectively disallows to use the keys assigned to accesskeys to be used for anything other than accessing those elements (e.g. you can no longer type those letters in an input), which is why this is not an acceptable solution.

I'm just showing it to demonstrate the general technical approach.

document.addEventListener('keypress', function(event) {
  const target = document.querySelector(`[data-accesskey=${event.key.toLowerCase()}]`);
  if (target) {
    target.focus();
    event.preventDefault();
  }
})
<input type="text" data-accesskey="n" placeholder="Press n to focus this field" />
<button type="button" data-accesskey="p">Press p to focus this button</button>

Upvotes: 2

Related Questions