kai.infotren/common/items.js

70 lines
1.5 KiB
JavaScript
Raw Normal View History

2022-07-13 00:33:59 +03:00
var currentIndex = 0
function findScrollParent(node) {
if (!node) {
return node
}
if (node.classList.contains('content') || node.tagName === 'body') {
return node
}
else {
return findScrollParent(node.parentNode)
}
}
2022-07-13 00:33:59 +03:00
function nav(offset) {
var items = document.querySelectorAll('.items:not(.disabled)')
currentIndex += offset
if (currentIndex < 0) {
currentIndex += items.length
}
if (currentIndex >= items.length) {
currentIndex -= items.length
}
2022-07-13 00:33:59 +03:00
items[currentIndex].focus()
if (items[currentIndex].getBoundingClientRect().y + items[currentIndex].getBoundingClientRect().height + 50 > document.documentElement.scrollHeight) {
findScrollParent(items[currentIndex]).scrollBy(0, 50)
}
2022-07-13 00:33:59 +03:00
items[currentIndex].addEventListener('keydown', handleKeyDown)
}
function handleKeyDown(e) {
2022-08-28 04:35:42 +02:00
if (e.target.classList.contains('items')) {
switch (e.key) {
case 'ArrowUp':
e.preventDefault()
e.stopPropagation()
nav(-1)
break
case 'ArrowDown':
e.preventDefault()
e.stopPropagation()
nav(1)
break
}
2022-07-13 00:33:59 +03:00
}
else if (e.target.name !== 'INPUT') {
switch (e.key) {
case 'ArrowUp':
case 'ArrowDown':
e.preventDefault()
e.stopPropagation()
nav(0)
break
}
}
2022-07-13 00:33:59 +03:00
}
window.addEventListener('load', function (e) {
// Select first item
var items = document.querySelectorAll('.items:not(.disabled)')
if (items.length > 0) {
items[0].focus()
items[0].addEventListener('keydown', handleKeyDown)
}
document.body.addEventListener('keydown', handleKeyDown)
})