How to send an event to a element in a relative position of the current element

367 Views Asked by At

I have a list of elements with the class .node-display, when one is clicked it becomes an input. I want to capture the down or up arrow keyups to click the very next .node-display in the list (relative to the current element).

In the below example, pressing down should click on item 5, and pressing up would click on item 3.

  • 1
  • 2
  • 3
  • 4 (Currently selected)
  • 5
  • 6

My best guess is something like this.

<input
   _="on keyup[key is 'ArrowDown'] send click to the first .node-display end"
>

Does anyone know how I'd actually write this expression?

1

There are 1 best solutions below

0
On

You probably want to put the behavior on the parent ul so you don't have to repeat it on every input.

Something like this:

<ul _="on keydown[key is 'ArrowDown'] from <input/> in me
           set nextSibling to it's parentElement's nextElementSibling
           if nextSibling
             set nextInput to the first <input/> in nextSibling
             call nextInput.focus()
             halt
           end
       on keydown[key is 'ArrowUp'] from <input/> in me
           set previousSibiling to it's parentElement's previousElementSibling
           if previousSibiling
             set previousInput to first <input/> in previousSibiling
             call previousInput.focus()
             halt
           end
       ">
  <li><input/></li>
  <li><input/></li>
  <li><input/></li>
  <li><input/></li>
</ul>

Some notes on this code:

  • I am using the from from in the event handler, which puts the element that the event came from into the it symbol
  • I am using the keydown event so we can cancel the event with the halt command, to avoid the down and up keys changing the caret position
  • I am using the halt command to stop the event from propogating
  • I used focus rather than click as a proof of concept