1

Have this code:

<li v-for="(dog, index) in dogs" :key="index" class=" hover:bg-gray-50" :class="{ 'bg-red-50': index === focus }" @keyup.enter="goToSlug(dog)"> .... </li>

I handle the focus perfectly, but want to run the method goToSlug() on key enter be pressed. It doesn't fire the method.

Riza Khan
  • 2,712
  • 4
  • 18
  • 42
Louis B
  • 306
  • 5
  • 18
  • You need the li element to have focus, for key events to fire. You can use vuejs refs to set focus to that element. – Bergur Aug 13 '21 at 00:03

1 Answers1

5

Key presses are only registered on items that have focus.

In order to make an element like a <li> tag focusable (which natively does not have that ability) you will need to add another attribute called tabindex='1' (1 being an arbitrary value here, but you can read more up on that here).

So in your case:

<li 
  v-for="(dog, index) in dogs" 
  tabindex="1" 
  :key="index" 
  class=" hover:bg-gray-50" 
  :class="{ 'bg-red-50': index === focus }" 
  @keyup.enter="goToSlug(dog)"
> .... 
</li>

Now, in order to register a key press on this (or its siblings) just tab through them and press enter when you have the desired target.

Riza Khan
  • 2,712
  • 4
  • 18
  • 42
  • 1
    It's better to add: tabindex="0", that way you let the browser decide the order in which the focuable-elements will be visited. If you choose for a non-negative number, you have to keep track of the tab-order, which is defined by tabindex – xiffy May 18 '22 at 12:46