1

I have following code. I have added overflow-y and max-height css property to the menu item popup. Inside search textbox when type 'a' and press down key the item selection change accordingly. But scroll is not moving. I want the scroll moves auto when moving on popup menu items

#myInputautocomplete-list{
          max-height:200px !important;
        overflow-y:auto !important;
}

<div class="autocomplete" style="width:300px;">
  <input id="myInput" type="text" name="myCountry" placeholder="Country">
</div>
<input type="submit">

Here Plnfkr

Muzafar Khan
  • 826
  • 3
  • 15
  • 28

1 Answers1

1

You can use Element.scrollIntoView() it can help you scroll in this case. I added these two lines at the end of the function inp.addEventListener("keydown", function(e)

if(x && x[currentFocus])
    x[currentFocus].scrollIntoView();
  • I forked the Pinfkr here
  • Documentation about scrollIntoView can be found here

Update:

It change scroll while we are on first element. It should change the scroll when item inside popup selection across the popup boundary

I fixed this issue by adding a function to check whether the scrolled element is visible, the scroll move is applied only when the element is not visible inside the dropdown.

// Return true/false if element is visible in relation to a given scrolling container
// Use to see if an element is visible within a scrolling div for example.
function isScrolledElementVisible(o_ele, o_container){
    var v_containerTop = o_container.scrollTop;
    var v_containerBottom = v_containerTop + o_container.offsetHeight;
    var v_elemTop = o_ele.offsetTop;
    var v_elemBottom = o_ele.offsetTop + o_ele.offsetHeight; 
    return ((v_elemBottom >= v_containerTop) && (v_elemTop <= v_containerBottom)
      && (v_elemBottom <= v_containerBottom) &&  (v_elemTop >= v_containerTop) );
}

for reference I got that function from here

Also if there is another scroll inside the page it also apply to them also

To solve this issue I'm manually setting the dropdown's scrollTop only instead of using scrollIntoView() so that other scrolls are not effected

  var topPos = x[currentFocus].offsetTop;
  o_container.scrollTop = topPos;

I learned how to not rely on scrollIntoView() from here

I forked the Pinfkr again it can be found here

omar.brome
  • 26
  • 6
  • Thanks for replaying but its not a good solution. It change scroll while we are on first element. It should change the scroll when item inside popup selection across the popup boundary. Also if there is another scroll inside the page it also apply to them also – Muzafar Khan Nov 22 '18 at 09:56
  • Welcome, I updated my original solution to solve the 2 issues you mentioned. Please check it again. – omar.brome Nov 22 '18 at 17:54
  • Thanks @omar.brome. Thumb up for you (y) – Muzafar Khan Nov 26 '18 at 06:50