This has been driving me mad for hours, I’m sure I’m missing something simple, or maybe not.
I’m using Javascript to turn my personal homepage into a console like application. You can view it here: http://www.fort-hub.com
I’m mapping key strokes and have backspace (keycode 8) to change the innerHTML property of the console input div called #in to have one less end character via slice() like so:
HTML:
<!doctype html>
<html lang='en-gb'>
<head>
<meta charset="UTF-8">
<title>FortHUB</title>
<link href="ss.css" rel="stylesheet" type="text/css">
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;">
</head>
<body>
<div id="console">
<div id="out"><h1>Welcome to fort-hub console</h1></div>
<div id="in">
<span id="text"></span><span id="cursor"><</span>
</div>
</div>
<script src="fH.js"></script>
</body>
</html>
Javascript:
/* Globals */
var _NL_ = '>';
var consoleIn = document.getElementById('text');
var consoleOut = document.getElementById('out');
/* Func in question */
function keyPress(event)
{
event.preventDefault();
event.stopPropagation();
var e = event || window.event;
var key = e.which || e.keyCode;
var keyChar;
var allowedChars = new Array();
allowedChars[0] = 8; /* backspace */
allowedChars[1] = 13; /* return */
allowedChars[2] = 32; /* space */
/* Alphanumeric range only */
if(key > 46 && key < 90 || inArray(allowedChars, key) === true)
{
keyChar = String.fromCharCode(key);
var input = trim(consoleIn.innerHTML);
/* Map backspace */
if(key === 8)
{
consoleIn.innerHTML = input.slice(0, -1);
}
...
consoleIn.innerHTML += keyChar.toLowerCase();
}
...
}
So, please test this out by going to the URL, typing something in and pressing backspace. One char will be removed but repeat backspaces will not remove the rest of the string’s chars.
If the pressed key was backspace, you remove the last character from the
input(and set the innerHTML toremain), yet you still add thekeyCharto theinnerHTML. This appends\x08(doesn’t show up depending on font and browser, isn’t accepted as input by Stackoverflow).Add a
returnstatement right after theconsoleIn.innerHTML = input.slice(0, -1);to abort the keypress-handler.