Nicoffee Nicoffee - 2 months ago 11
HTML Question

Window scroll with list

I'm trying to create navigatable list at top of the page.
So i have

<ul>
with some
<li>
inside. I don't need to show full list, couse i might have many of them. And i need to have opportunity to navigate inside this list with keyboard.
I add to li's
tabindex='0'
attribute.
The problem is, window start to scroll with list, after bottom elements is focused.

HTML:

<ul>
<li tabIndex="0">item 1</li>
<li tabIndex="0">item 2</li>
<li tabIndex="0">item 3</li>
<li tabIndex="0">item 4</li>
<li tabIndex="0">item 5</li>
<li tabIndex="0">item 6</li>
<li tabIndex="0">item 7</li>
<li tabIndex="0">item 8</li>
<li tabIndex="0">item 9</li>
<li tabIndex="0">item 10</li>
<li tabIndex="0">item 11</li>
<li tabIndex="0">item 12</li>
<li tabIndex="0">item 13</li>
<li tabIndex="0">item 14</li>
<li tabIndex="0">item 15</li>
<li tabIndex="0">item 16</li>
</ul>


JS:

$('li').on('focus', function() {
$(this).addClass('focused');
});

$('li').on('focusout', function() {
$(this).removeClass('focused');
});

$('li').keydown(function (e) {
if (e.keyCode == 38) {
$(e.target).prev().focus();
}
if (e.keyCode == 40) {
$(e.target).next().focus();
}
});


Fiddle: https://jsfiddle.net/xne2p3mo/1/

Answer

Put e.preventDefault(); in the keydown callback, or also you can check, when it should prevent defaults, like scrolling window.

$('li').keydown(function (e) {
    if (e.keyCode == 38 || e.keyCode == 40) {
        e.preventDefault();
    }
    e.preventDefault();
    if (e.keyCode == 38) {
        $(e.target).prev().focus();
    }
    if (e.keyCode == 40) {
        $(e.target).next().focus();
    }
});
Comments