Navigate through list using arrow keys? (JavaScript/JQ)
Asked Answered
M

4

19

I can't seem to find an answer to how to accomplish this, yet it's a feature I've seen several times. Essentially I'm echoing out a list and I would like to create the ability to highlight and select these items using arrow keys/enter. Can someone help give me an idea as to how I can accomplish this? I know how to use keycodes (of course), just not how to turn that into functioning code for selecting items on a list...

I was thinking maybe I'd have to have some sort of hidden radio button to mark it as selected or not... but even then I don't know how I would jump from one radio button to the other up and down the list. So if anyone could give me a hand with this I'd really appreciate it. Thank you.

Metatarsal answered 17/1, 2012 at 22:48 Comment(0)
M
55

Since you didn't really explain what you're having trouble with, I just created a general solution. Hopefully this helps:

var li = $('li');
var liSelected;
$(window).keydown(function(e) {
    if(e.which === 40) {
        if(liSelected) {
            liSelected.removeClass('selected');
            next = liSelected.next();
            if(next.length > 0) {
                liSelected = next.addClass('selected');
            } else {
                liSelected = li.eq(0).addClass('selected');
            }
        } else {
            liSelected = li.eq(0).addClass('selected');
        }
    } else if(e.which === 38) {
        if(liSelected) {
            liSelected.removeClass('selected');
            next = liSelected.prev();
            if(next.length > 0) {
                liSelected = next.addClass('selected');
            } else {
                liSelected = li.last().addClass('selected');
            }
        } else {
            liSelected = li.last().addClass('selected');
        }
    }
});

JSFiddle: http://jsfiddle.net/Vtn5Y/

Melville answered 17/1, 2012 at 23:9 Comment(4)
Well that's exactly what I was having trouble with, so thank you.Metatarsal
If the element is not a link, how would you use the keyboard's "Enter" key to select the element?Melainemelamed
if(e.which === 13){ $(".selected").click(); }Ameeameer
I would add preventDefault() to prevent window scrolling down\up - right after "if (e.which ===40){ e.preventDefault();.... } else if (e.which ===38){ e.preventDefault(); } orGauger
L
15

My example for native JavaScript

var ul = document.getElementById('list');
var liSelected;
var index = -1;

document.addEventListener('keydown', function(event) {
    var len = ul.getElementsByTagName('li').length-1;
    
    // DOWN ARROW 
    if(event.which === 40) {
        index++;

        if (liSelected) {
            removeClass(liSelected, 'selected');
            next = ul.getElementsByTagName('li')[index];

            if(typeof next !== undefined && index <= len) {
                liSelected = next;
            }
            else {
                index = 0;
                liSelected = ul.getElementsByTagName('li')[0];
            }

            addClass(liSelected, 'selected');
            console.log(index);
        }
        else {
            index = 0;
            liSelected = ul.getElementsByTagName('li')[0];
            addClass(liSelected, 'selected');
        }
    }
    // UP ARROW
    else if (event.which === 38) {
        if (liSelected) {
            removeClass(liSelected, 'selected');
            index--;
            next = ul.getElementsByTagName('li')[index];

            if(typeof next !== undefined && index >= 0) {
                liSelected = next;
            }
            else {
                index = len;
                liSelected = ul.getElementsByTagName('li')[len];
            }

            addClass(liSelected, 'selected');
        }
        else {
            index = 0;
            liSelected = ul.getElementsByTagName('li')[len];
            addClass(liSelected, 'selected');
        }
    }
}, false);

function removeClass(el, className) {
    if(el.classList) {
        el.classList.remove(className);
    } else {
        el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
    }
};

function addClass(el, className) {
    if(el.classList) {
        el.classList.add(className);
    } else {
        el.className += ' ' + className;
    }
};
li.selected {background:yellow}
<ul id="list">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
</ul>

https://jsfiddle.net/m6watqpe/

Lycanthropy answered 31/8, 2017 at 15:20 Comment(0)
C
7

2020 Update

In case someone wants to do this in Vue.js , I have added the code below with comments wherever necessary and rest is self explanatory

HTML

<script type="text/x-template" id="list">
  <div id="list-container" ref="root">
    <div v-for="item in items" :key="item.id" class="list-item" :class="item.id === selectedId ? 'selected': ''" @click="select(item.id)">
      {{item.value}}
    </div>
  </div>
</script>

<div id="app">
  <list></list>
</div>

CSS

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

html {
  height: 100%;
}

body {
  height: 100%;
  min-height: 100%;
  padding: 1rem;
  font-family: 'Tahoma', sans-serif;
}

.list-item {
  padding: 1rem 0.25rem;
}

.selected {
  background: lightyellow;
}

JS

const items = new Array(100).fill(null).map((item, index) => {
  return { id: index, value: "Item " + index };
});

// https://mcmap.net/q/378401/-scroll-to-element-only-if-not-in-view-jquery
function scrollIntoViewIfNeeded(target) {
    var rect = target.getBoundingClientRect();
    if (rect.bottom > window.innerHeight) {
        target.scrollIntoView(false);
    }
    if (rect.top < 0) {
        target.scrollIntoView();
    } 
}

Vue.component("list", {
  template: "#list",
  data() {
    return {
      items,
      selectedId: 0
    };
  },
  methods: {
    select(itemId) {
      this.selectedId = itemId;
      scrollIntoViewIfNeeded(this.$refs.root.children[itemId])
      // this.$refs.root.children[item.id].scrollIntoView({ behavior: "smooth" });
    },
    handleKeyDown(event) {
      switch (event.keyCode) {
        // In case of left arrow key move to the last item
        case 37:
          if (this.selectedId > 0) {
            this.select(this.selectedId - 1);
          }
          // Prevent the default scroll event from firing
          event.preventDefault();
          break;
        // In case of up arrow key, move to the last item
        case 38:
          if (this.selectedId > 0) {
            this.select(this.selectedId - 1);
          }
          event.preventDefault();
          break;
        // In case of right arrow key, move to the next item
        case 39:
          if (this.selectedId < this.items.length - 1) {
            this.select(this.selectedId + 1);
          }
          event.preventDefault();
          break;
        // In case of down arrow key, move to the next item
        case 40:
          if (this.selectedId < this.items.length - 1) {
            this.select(this.selectedId + 1);
          }
          event.preventDefault();
          break;
      }
    }
  },
  mounted() {
    window.addEventListener("keydown", this.handleKeyDown);
  },
  destroyed() {
    window.removeEventListener("keydown", this.handleKeyDown);
  }
});

new Vue({
  el: "#app"
});
Camembert answered 21/1, 2020 at 4:16 Comment(1)
While this code is vue specific, it can easily be applied elsewhere. Nice!Leyba
M
0

This may depend on the browser. It seems to work only if the radio inputs are next to each other (label is also ok).

<input type="radio" ... /> 
<input type="radio" ... />
<input type="radio" ... />

But this will break radio navigation in Firefox and probably other browsers:

<div><input type="radio" ... /> ... </div>
<div><input type="radio" ... /> ... </div>

This is annoying as soon as you want to make something a bit more complex than a simple list (categories...).

Mcnally answered 13/1, 2014 at 15:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.