0

If I have a div with a set height, and a long list of items within it that you can scroll down through using the arrow keys, how can I keep the current selected item in view?

Here is a link to the code I've been attempting:

https://jsfiddle.net/uaxupagu/8/

$(document).ready(function(e) {
  var index = 0;

  for (var i = 0; i < 100; i++) {
    $("<li />", {
      "id": "item" + i,
      "text": "test " + i
    }).appendTo("#ul_par");
  }

  $(document).bind("keydown", function(e) {
    var code = e.keyCode || e.which;
    if (code == 40) {
      index = index + 1;
    } else {
      index = index - 1;
    }

    $("#ul_par li").css("background", "#fff");
    $("#ul_wrapper").animate({
      scrollTop: $("#item" + index).offset().top + "px"
    }, 1000);
    $("#item" + index).css("background", "#ff0000");
  })
});
#ul_wrapper {
  height: 50px;
  overflow: auto;
  border: 1px solid #d3d3d3;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ul_wrapper">
  <ul id="ul_par"></ul>
</div>

thank you for your time

------EDIT----------

I found the answer within this post:

How do I scroll to an element within an overflowed Div?

Sorry for the duplicate

RON2015
  • 304
  • 2
  • 14
  • How do you select an item? Are you expecting the `text N` item to stay in position? This seems a little odd as it will cover most of the selection box, making it hard to select anything else...? – Rory McCrossan Apr 23 '18 at 17:56
  • I really didn't understand what you mean by *"you can scroll down through using the arrow keys, how can I keep the current selected item in view"* – Ricardo Pontual Apr 23 '18 at 17:58
  • if you click in the example and begin pressing the down arrow you will see one highlight in red, as you press down it keeps selecting the next item down. I want the div to scroll and keep the LI in view. Right now It has a strange behavior of animating up and down..not really keeping in view. – RON2015 Apr 23 '18 at 18:02

0 Answers0