1

I implemented a function to navigate through a list and scroll when I hit the last item visible in the list, this is my code so far:

const arrowNavigation = (
    e: React.KeyboardEvent<HTMLInputElement>
  ) => {
    if (selectedCountry.current) console.log(selectedCountry.current.last());
    if (e.key === 'ArrowDown') {
      if (selectedCountryIndex < autoCompleteSuggestions.length - 1)
        setSelectedCountryIndex(selectedCountryIndex + 1);
      if (selectedCountryIndex > 3)
        if (selectedCountry.current && dataList.current) {
          console.log(selectedCountry.current.offsetHeight);
          dataList.current.scrollTop +=
            selectedCountry.current.offsetHeight;
        }
    } else if (e.key === 'ArrowUp') {
      if (selectedCountryIndex - 1 >= 0)
        setSelectedCountryIndex(selectedCountryIndex - 1);
      if (selectedCountryIndex > 3)
        if (selectedCountry.current && dataList.current) {
          dataList.current.scrollTop -=
            selectedCountry.current.offsetHeight;
        }
    } else if (e.key === 'Enter') {
      if (textInput.current)
        textInput.current.value =
          autoCompleteSuggestions[selectedCountryIndex];
      setInputValue(autoCompleteSuggestions[selectedCountryIndex]);
    }
  };

This is the view currently: enter image description here

To explain the code:

dataList is the ul.

selectedCountry is the li element that I am currently on.

selectedCountryIndex is the index of element that I am currently on.

autoCompleteSuggestions is a list of country suggestions based on the input I've given.

So my approach was to wait till selectedCountryIndex is at a certain point to start scrolling but this is really just a hardcoded solution if my list view has more visible items it wouldn't really work, is there a way to know how many visible items the ul has? or maybe know the position of the visible items in the ul (like first last and so on..).

enter image description here

Also, as you can see in the gif when I scroll down it works perfectly, but when I scroll up, I start seeing the next element little by little, I am not sure why that's happening, so if you have any idea about that as well let me know.

1 Answer 1

1
 const ul = document.getElementById('dataList');
  let li = ul.getElementsByTagName('li')[mIndex + 1];
  li?.scrollIntoView({
    behavior: 'smooth',
    block: 'end',
  }); // my pseudocode using element ids
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer, I'll try it and let you know!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.