Skip to content

Instantly share code, notes, and snippets.

@worr
Created April 19, 2012 03:53
Show Gist options
  • Select an option

  • Save worr/2418404 to your computer and use it in GitHub Desktop.

Select an option

Save worr/2418404 to your computer and use it in GitHub Desktop.
I made a console!
var jsconsole = (function() {
var prompt = ">";
var cursor = "_";
var text = "";
var cursor_displayed = true;
var history = [];
var history_cursor = -1;
var jsconsole_div;
var history_div;
var jsconsole = { on_command: function (text) { console.log("butt"); } };
jsconsole.prototype = Object.prototype;
jsconsole.prototype.start = function() {
jsconsole_div = document.querySelector("#line");
history_div = document.querySelector("#history");
jsconsole_div.innerHTML = prompt + text + cursor;
setInterval(function() {
old_html = jsconsole_div.innerHTML;
if (cursor_displayed) {
jsconsole_div.innerHTML = old_html.slice(0, old_html.length - 1);
} else {
jsconsole_div.innerHTML = old_html + cursor;
}
cursor_displayed = !cursor_displayed;
}, 500);
};
jsconsole.prototype.keypress = function(event) {
if (event.ctrlKey || event.altKey || event.metaKey)
return;
// Backspace and delete, respectively
if (event.which == 8 || event.which == 46) {
text = text.slice(0, text.length - 1);
} else if (event.which == 13) {
// Enter key
if (cursor_displayed) {
jsconsole_div.innerHTML = jsconsole_div.innerHTML.slice(0, jsconsole_div.innerHTML.length - 1);
}
if (history_div.innerHTML) {
history_div.innerHTML += "<br />";
}
history_div.innerHTML += jsconsole_div.innerHTML;
history.unshift(text);
history_cursor = -1;
if (!self.process_command(text) && text)
jsconsole.on_command(text);
text = "";
} else if (event.keyCode == 38) {
// Up arrow
if (history_cursor + 1 < history.length) {
text = history[++history_cursor];
}
} else if (event.keyCode == 40) {
// Down arrow
if (history_cursor > 0) {
text = history[--history_cursor];
} else if (history_cursor == 0) {
text = "";
history_cursor--;
}
} else if (event.keyCode == 9) {
text = "\t" + text;
} else {
text += String.fromCharCode(event.which);
}
jsconsole_div.innerHTML = prompt + text + cursor;
cursor_displayed = true;
window.scrollTo(0, document.body.scrollHeight);
if (event.which == 8 ||
event.which == 46 ||
event.keyCode == 38 ||
event.keyCode == 40 ||
event.keyCode == 13 ||
event.keyCode == 9)
event.stopPropagation();
};
jsconsole.prototype.process_command = function(command) {
if (command == ";clear") {
history_div.innerHTML = "";
return true;
}
return false;
};
return jsconsole;
})();
document.addEventListener("DOMContentLoaded", jsconsole.start);
document.addEventListener("keypress", jsconsole.keypress, true);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment