Skip to content

Instantly share code, notes, and snippets.

@julianwachholz
Last active August 28, 2020 10:04
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save julianwachholz/6480f73d2c0e221f55cc to your computer and use it in GitHub Desktop.
Save julianwachholz/6480f73d2c0e221f55cc to your computer and use it in GitHub Desktop.
JavaScript <input> history with arrow buttons, a.k.a. poor man's readline
/**
* License: WTFPL - http://www.wtfpl.net/
*
* Usage: element.addEventListener('keydown', inputHistory());
*/
function inputHistory(max_history) {
var PREV = 38, NEXT = 40, ENTER = 13,
history = [''], current = 0;
if (!max_history) {
max_history = 100;
}
return function (event) {
switch (event.which) {
case ENTER:
if (this.value.trim().length) {
history[current] = this.value;
history.unshift('');
current = 0;
if (history.length > max_history) {
history = history.slice(0, max_history);
}
}
break;
case PREV:
if (current + 1 < history.length) {
event.preventDefault();
history[current] = this.value;
current += 1;
this.value = history[current];
}
break;
case NEXT:
if (current - 1 >= 0) {
event.preventDefault();
history[current] = this.value;
current -= 1;
this.value = history[current];
}
break;
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment