Saia Fonua
Saia Fonua

Reputation: 45

How to down key or up key through a list to trigger focus on an item inside an event listener?

I’m trying to run a focus() method on a particular element node depending on if the up arrow key is pressed or down arrow key is pressed. The items of the list I want to focus on are children of a sibling node that I'm listening, because I would like the focus to go from the search box (input tag) to the children nodes of the sibling node.

I put the firstChild property on the searchSuggest box inside the event listener when the down arrow key is pressed, however, that will run the focus() method on the first child or list item each time it is pressed, and not the next sibling in the list.

  const d = document,     
    searchBox = d.getElementById("PFsearchBox"),
    searchSuggest = d.getElementById("PFsearchSuggest")


  searchBox.addEventListener("keydown", e => {
    // up arrow
    if (e.which === 38) {
        e.preventDefault();
        // select the last item in the suggestion list
        searchSuggest.children[searchSuggest.children.length - 1].focus()
    }

    // down arrow
    if (e.which === 40) {
    e.preventDefault();
    searchSuggest.firstChild.focus()
    }
  });

I expect when the down arrow key is pressed, the focus goes from the input box, to the first child list item in the searchSuggest node, and then sequentially down the list each time the down arrow key is pressed, and vice versa when the up arrow key is pressed.Image of the HTML Markup of the DOM nodes

Upvotes: 0

Views: 1144

Answers (1)

Marcos Vini
Marcos Vini

Reputation: 1

 onKeyDown={(e) => {    
      if (["Enter", "ArrowDown"].includes(e.key)) {
           let inputs = document.querySelectorAll('input')
           inputs = Array.from(inputs)
           let index_input = inputs.indexOf(document.getElementById(e.target.id))
           let next = inputs[index_input + 2]
           next.focus()
                   
          atualiza_valor(params.row, e.target.value)
        
        }
       
                 if (["ArrowUp"].includes(e.key))   {
                   let inputs = document.querySelectorAll('input')
                   inputs = Array.from(inputs)
                   let index_input = inputs.indexOf(document.getElementById(e.target.id))
                   let next = inputs[index_input - 2]
                   next.focus()  
                 }
               }}

Upvotes: -1

Related Questions