Custom key navigation: get element in focus #2802
-
QuestionHi, I try to implement a custom key navigation and struggle to find an easy way to obtain the current element that is in focus. Therefore, I am wondering if there any way to get the current element in focus? This is what I have so far: from nicegui import ui
from nicegui.events import KeyEventArguments
def key_navigation(e: KeyEventArguments, container):
current_element = 1 # how to adapt this dynamically?
if e.action.keydown:
if e.key.arrow_up and current_element>0:
ui.notify('going up')
container[(current_element-1)].run_method('focus')
elif e.key.arrow_down and current_element<max(container.keys()):
ui.notify('going down')
container[current_element+1].run_method('focus')
container = {}
with ui.column():
container[0] = ui.input("A")
container[1] = ui.input("B")
container[2] = ui.input("C")
keyboard = ui.keyboard(on_key=lambda e: key_navigation(e, container),
active= True,
repeating=False,
ignore = [])
ui.run() I would be very glad if any of you has an idea on how to obtain information about the element in focus or on how to achieve this navigation behaviour in a different way. Thank you and best, PS: I am aware that one can use tab to switch from one element to another and "change the directionality" by grouping elements into ui.row() and ui.column(). However, I would like to enable key navigation by row and column.... |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Hi @bmrast, I'd suggest to track "focus" events on the input elements like this: def handle_key(e: KeyEventArguments) -> None:
if e.action.keydown:
if e.key.arrow_up and focus['index'] > 0:
container[focus['index']-1].run_method('focus')
elif e.key.arrow_down and focus['index'] < len(container) - 1:
container[focus['index']+1].run_method('focus')
with ui.column():
container = [
ui.input('A'),
ui.input('B'),
ui.input('C'),
]
focus = {'index': 0}
for element in container:
element.on('focus', lambda element=element: focus.update({'index': container.index(element)}))
ui.keyboard(on_key=handle_key, ignore=[]) |
Beta Was this translation helpful? Give feedback.
-
Nice, this works perfectly :) Best, |
Beta Was this translation helpful? Give feedback.
Hi @bmrast,
I'd suggest to track "focus" events on the input elements like this: