Skip to content
This repository has been archived by the owner on May 27, 2019. It is now read-only.

Keyboar selection in list using arrow keys #152

Closed
Closed
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 30 additions & 2 deletions chrome/script.browserify.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ function view() {

return [
// search form
m("div.search", [
m("div.search", { onkeydown: keyHandler }, [
m(
"form",
{
Expand All @@ -54,6 +54,7 @@ function view() {
[
m("input", {
type: "text",
id: "search-field",
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm using id for selecting and detecting focus on input. It seemed to be better than reading other attributes (like tagName) to me.

name: "s",
placeholder: "Search password..",
autocomplete: "off",
Expand All @@ -69,7 +70,7 @@ function view() {
]),

// results
m("div.results", results)
m("div.results", { onkeydown: keyHandler }, results)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As you can see handler is assigned to a container of results and container of input. I did it because I didn't want to change structure without asking you first. Alternatively, we can add a new extra container to render or use native API to register the handler.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't mind wrapping both containers in a some kind of parent container, and assigning the onkeydown to it. But if for whatever reason it gets complicated, the current solution is also fine.

];
}

Expand Down Expand Up @@ -149,3 +150,30 @@ function getLoginData() {
}
);
}

// This function uses regular DOM
// therefore there is no need for redraw calls
function keyHandler(e) {
switch (e.key) {
case 'ArrowUp':
switchFocus('button.login:last-child', 'previousElementSibling');
break;

case 'ArrowDown':
switchFocus('button.login:first-child', 'nextElementSibling');
break;
}
}

function switchFocus(firstSelector, nextNodeAttr) {
var inputId = 'search-field';
var newActive = document.activeElement.id === inputId ?
document.querySelector(firstSelector) :
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is using querySelector. Compatibility should be probably fine due to browser selection. https://www.w3schools.com/jsref/met_document_queryselector.asp

document.activeElement[nextNodeAttr];

if (newActive) {
newActive.focus();
} else {
document.getElementById('search-field').focus();
}
}