Last active
December 17, 2015 00:29
-
-
Save delba/5521586 to your computer and use it in GitHub Desktop.
Keyboard navigation on list
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| container = document.getElementById('items') | |
| new List(container) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class List | |
| constructor: (@container) -> | |
| document.addEventListener 'keypress', (e) => | |
| return if document.activeElement.tagName in ['INPUT', 'TEXTAREA'] | |
| switch e.keyCode || e.charCode | |
| when 106 then @selectNext() | |
| when 107 then @selectPrev() | |
| else return | |
| selectNext: -> | |
| unless @selected | |
| @select @container.firstElementChild | |
| return | |
| @select @selected.nextElementSibling | |
| @scroll() | |
| selectPrev: -> | |
| unless @selected | |
| return | |
| @select @selected.previousElementSibling | |
| @scroll() | |
| select: (element) -> | |
| return unless element | |
| @selected?.classList.remove 'selected' | |
| element.classList.add 'selected' | |
| @selected = element | |
| scroll: -> | |
| rectObject = @selected.getBoundingClientRect() | |
| if rectObject.top < 0 | |
| @selected.scrollIntoView() | |
| else if rectObject.bottom > innerHeight | |
| @selected.scrollIntoView(false) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment