Change not working in Phoenix LiveView for Key HJKL

In Phoenix LiveView example for the snake, I want to change the ArrowLeft/ArrowDown/ArrowUp/ArrowRight to KeyH/KeyJ/HeyK/KeyL, but not working. If I change to F5/F6/F7/F8 it works, here is the code before and after:

Original:

   defp turn(socket, "ArrowLeft"), do: go(socket, :left)
   defp turn(socket, "ArrowDown"), do: go(socket, :down)
   defp turn(socket, "ArrowUp"), do: go(socket, :up)
   defp turn(socket, "ArrowRight"), do: go(socket, :right)

Changed to this, but not working:

   defp turn(socket, "KeyH"), do: go(socket, :left)
   defp turn(socket, "KeyJ"), do: go(socket, :down)
   defp turn(socket, "KeyK"), do: go(socket, :up)
   defp turn(socket, "KeyL"), do: go(socket, :right)

This one works:

   defp turn(socket, "F5"), do: go(socket, :left)
   defp turn(socket, "F6"), do: go(socket, :down)
   defp turn(socket, "F7"), do: go(socket, :up)
   defp turn(socket, "F8"), do: go(socket, :right)

Any idea why it works for Function keys but not A-Z ?

:wave:

Would probably be h according to https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key. Check what your live view process actually receives.

3 Likes

It works, thanks, couldn’t be more simple. :grinning: