Last active
August 28, 2020 10:04
-
-
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
This file contains 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
/** | |
* 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