MapMyGlobe

Web Command Line

It is a secret for nobody that I am fond of neat DOM scripting and Javascript widgets, especially those that try to bring the Web to the level of User Interaction present in desktop applications. Well, one of the user interfaces that examplify the desktop applications is the command line.

The tiny javascript function I’m writing down here brings any of your html form input lines into life… well, that is to say, into command-line-style history behavior. Just type anything into the input below and press enter. You can then retrieve your previous entries by pressing the up and down arrows, like in a desktop interface.





Like it? Here’s the code:

var cmdHistory = [];

function cmdExec(){
  var cmd = $F("cmdline");
  cmdHistory.unshift(cmd);
  $("cmdline").value='';
  cmdPos=-1;
}

function keypr(e){
  var code;
  if (!e) var e = window.event;
  if (e.keyCode) code = e.keyCode;
  else if (e.which) code = e.which;
  if (code==38 && cmdPos
    cmdPos++;
    $(”cmdline”).value = cmdHistory[cmdPos];
  }
  if (code==40 && cmdPos==0){
    cmdPos–;
    $(”cmdline”).value=”;
  }
  if (code==40 && cmdPos>0){
    cmdPos–;
    $(”cmdline”).value = cmdHistory[cmdPos];
  }
}

var cmdPos=-1;

and here’s the Html:

<form id="command" name="command" action="#" onsubmit="cmdExec(); return false">
  <input id="cmdline" style="font-family: monospace; width: 400px"
            onkeypress="keypr(event);" type="text" />
</form>

The key point is to use Javascript’s unshift() method, which is the equivalent of push(), but inserting at the beginning of the array. Hope you’ll find this snippet useful.

2 Responses to “Web Command Line”

  1. Joy Says:

    This is pretty nice, except for the fact that it’s stand-alone and hard to see how to integrate it with a real page.
    I couldn’t quite make out what you were doing until I read on some other site about the prototype script library. You might want to mention that you’re using it, so the syntax makes sense to people.

  2. Julien Says:

    I do use $() and $F() functions, which are, as far as I know, pretty standard across Javascript frameworks such as Prototype, Mootools, jQuery, etc. (They can have slightly different meanings, though).

    And yeah, it is stand-alone, but you could integrate it with a real page very easily. The restriction is that the page needs to be Ajax (no POST form, for example). In that case you would just add the Ajax-related function to the form’s onsubmit, right after cmdExec().

Leave a Reply