Skip to content

Instantly share code, notes, and snippets.

@s1sw
Created January 25, 2018 23:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save s1sw/0b3544acfbda0fe2bbb206e4266ba50b to your computer and use it in GitHub Desktop.
Save s1sw/0b3544acfbda0fe2bbb206e4266ba50b to your computer and use it in GitHub Desktop.
A simple fake terminal in Javascript. Requires ES6 and jQuery, but could easily be changed to not use these.
/* global $ */
window.terminalCommands = {};
var terminalElement = undefined;
var templateCommand = undefined;
var currentCommandElement = undefined;
function writeOutput(outputString) {
var outputElement = document.createElement("div");
outputElement.innerHTML = outputString;
terminalElement.append(outputElement);
}
function createNewCurrentCommandElement() {
if(currentCommandElement !== undefined) {
currentCommandElement.off("keypress");
currentCommandElement.children(".terminal-input").attr("contenteditable", "false");
}
currentCommandElement = templateCommand.clone(true);
currentCommandElement.attr("id", "");
currentCommandElement.keypress(onCommandEntryKeypress);
terminalElement.append(currentCommandElement);
currentCommandElement.children(".terminal-input").focus();
}
function onCommandEntered(commandString) {
console.log(commandString);
var args = commandString.split(" ");
var command = args[0];
args = args.splice(1);
var outputString;
if(window.terminalCommands.hasOwnProperty(commandString)) {
outputString = window.terminalCommands[commandString](args);
}
else {
outputString = commandString + ": command not found";
}
writeOutput(outputString);
createNewCurrentCommandElement();
}
function onCommandEntryKeypress(event) {
if(event.which == 13) {
event.preventDefault();
onCommandEntered(currentCommandElement.children(".terminal-input").text());
}
}
$(document).ready(() => {
terminalElement = $("#terminal");
templateCommand = terminalElement.children("#command-template");
createNewCurrentCommandElement();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment