1

I have made an search function where you can navigate the results with your keyboard arrows. All results will show up in li's inside a div with style:

overflow:auto; max-height: 100px;

I focus the first li with this code:

$('#searchInput').keydown(function(e) {
    if (e.keyCode==40) {
        $('li:first').focus();
    }
});

The div with overflow:auto will then auto scroll so the first focused li won't be visible...

Here is an example: http://jsfiddle.net/CZz9n/1/

rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
Hullo
  • 13
  • 2
  • 3
    What is the question/what isn't working the way you want it to? – robooneus Aug 15 '13 at 14:31
  • @robooneus I think the part that isn’t working is the second-to-last paragraph. “The div with `overflow: auto` will then auto scroll so the first focused `li` won’t be visible.” When you press the down arrow like the text field in the demo says, the first item is selected but scrolls out of sight. It should be selected and stay visible. – Rory O'Kane Aug 15 '13 at 14:41

1 Answers1

4

The scrolling down comes from the browser default behavior of interpreting the down arrow as a command to scroll down. To fix this, you just need to prevent the default behavior.

You have already prevented the default behavior in the keydown handler for the lis, which is just what we need. You used return false, but e.preventDefault() is slightly safer.

$('#searchInput').keydown(function(e) {
    if (e.keyCode==40) {
        e.preventDefault(); // add this
        $('li:first').focus();
    }
});

jsFiddle

Community
  • 1
  • 1
Rory O'Kane
  • 29,210
  • 11
  • 96
  • 131
  • Isn't `return false` a bit overkill? `e.preventDefault()` should suffice. – rink.attendant.6 Aug 15 '13 at 14:50
  • 3
    @rink.attendant.6 I had forgotten [the difference](http://stackoverflow.com/q/1357118/578288), so I had just copied the `return false` from the other lines. Yes, `e.preventDefault()` [works too](http://jsfiddle.net/roryokane/mDVyb/), and I guess it’s a bit safer. – Rory O'Kane Aug 15 '13 at 14:53