Using Javascript with Textfields

I'm going to look at different ways to manipulate textboxes using javascript. All of these examples are things I've had to use for various projects.

Here's what I'll cover:

  • Selecting text on focus
  • Creating a live preview
  • Keyboard shortcuts (ie. ctrl+b to bold text)
  • Advanced macros

Selecting Text On Focus

Let's start with the easy one. Here's the scenario: you have HTML code in a textbox that you want people to copy and paste. When the user clicks the textbox, the text should be highlighted.

<textarea onFocus='this.select();'>Click to select</textarea>
Example:

Creating a Live Preview

Here's the scenario: You allow users to create their own html template. You want them to see a live preview of the rendered HTML code as they type.

First, the javascript.

//Puts html in the preview pane
function updatePreview(html) {
  //Get preview element
  target = document.getElementById('preview');
  //Replace element's contents with passed text
  target.innerHTML = html;
}

Now, the html.

<!--Text area that user types in-->
<textarea onKeyUp='updatePreview(this.value);'></textarea>

<!--Element where preview is displayed-->
<div id='preview'></div>
Example:
Preview
No Text
Type HTML code here:

Keyboard Shortcuts

Here's the scenario: When a user fills out a textbox, you want their progress to be saved when they hit ctrl+s (Control + S), the standard keyboard shortcut for "save".

To actually save the data to a database, Ajax is required. I may get to this in a later tutorial, but for now, I'll assume you have a javascript function "saveData()" that does this. Here's the javascript.

//Find out which key is pressed
function interpretKey(e) {
  //Get window event (handle different browsers)
  e = (e) ? e : window.event;

  //Get key code (handle different browsers)
  key = (e.keyCode) ? e.keyCode : event.which;
  
  if(e.ctrlKey) //Control Key is pressed
    if(key==83) //S key is pressed
      saveData(); //Save the data
}

And here's the HTML.

<textarea onKeyDown='interpretKey(event);'></textarea>
Example:

Advanced Macros

A macro is a function that performs several tasks. They are often used to automate actions that humans repeatedly perform. I'm going to use the keyboard shortcuts we just made to preform macros.

Let's say you often type the following skeleton for an HTML file in a textfield:

<html>
<head>
  <title>title</title>
</head>

<body>

</body>
</html>

You want to automate this so you don't have to type it every time. Let's make the keyboard shortcut "Alt+1" type this for you.

First, the javascript.

//Define array of macros
var macros = new Array;

//Define first macro
macros[0] = {
  //Name of macro
  "name":
    "HTML Skeleton",
  //Key that triggers Macro
  "key":
    49, // "1" key
  //Text to insert into textbox
  "text": 
    "<html>\n"+
    "<head>\n"+
    "  <title>title</title>\n"+
    "</head>\n"+
    "<body>\n\n</body>\n"+
    "</html>",
  //Where to place cursor after inserting (from start of insert)
  "cursor_offset":
    52 //Places cursor 52 characters from start (Between the <body> tags)
};
function handleMacro(e) {
  //Get window event (handle different browsers)
  e = (e) ? e : window.event;

  //Get key code (handle different browsers)
  key = (e.keyCode) ? e.keyCode : event.which;
  
  if(e.altKey) { //Alt Key is pressed, check for macros
    for(i=0;i<macros.length;i++) {
      if(macros[i].key == key) { //One of the macros matches the key pressed
        //Do the macro
        addText01(macros[i].text,macros[i].cursor_offset);
    }
  }
  }
}
function addText01(text,offset) {
  //Get textbox element
  textbox = document.getElementById("textbox");
  
  //Get current cursor position.  This is where the text will be inserted.
  cursorPosition = getCursorPosition(textbox);
  if(cursorPosition==-1)
    return false;
  
  //Get the current text in the textbox
  currentText = textbox.value;
  
  //Generate new value with new text inserted
  newText = currentText.substr(0,cursorPosition) + text + currentText.substr(cursorPosition);
  textbox.value = newText;
  
  //Get the new cursor position
  if(offset || offset=='0') //Offset defined
    newCursorPosition = offset;
  else
    newCursorPosition = text.length;
    
  //Set the new cursor position
  setCursorPosition(textbox,cursorPosition+newCursorPosition);
  
  return true;
}
function getCursorPosition(node) {
//Firefox support
  if(node.selectionStart) return node.selectionStart;
//Catch Exception (unsupported browser)
  else if(!document.selection) return 0;
//IE support
    //Define character to search for
  var c = "\001";
  //Create empty range
  var sel  = document.selection.createRange();
  //Duplicate range
  var dul  = sel.duplicate();
  var len  = 0;
  //Move duplicate range to node
  dul.moveToElementText(node);
  //Set selected value to character
  sel.text = c;
  //Search for character
  len  = (dul.text.indexOf(c));
  //Delete character
  sel.moveStart('character',-1);
  sel.text = "";
  //Return character position
  return len;
}
function setCursorPosition (node, pos) {
// Firefox support
  if (node.selectionStart || node.selectionStart == '0') {
    node.selectionStart = pos;
    node.selectionEnd = pos;
    return;
  }
  
// IE Support
    // Create empty selection range
  var sel = document.selection.createRange ();
  // Move selection start and end to 0 position
  sel.moveStart ('character', -node.value.length);
  // Move selection start and end to desired position
  sel.moveStart ('character', pos);
  sel.moveEnd ('character', 0);
  sel.select ();
}

Now for the HTML.

<textarea id='textbox' onKeyDown='handleMacro(event);'></textarea>

Using this technique, you can easily define multiple macros. For a list of javascript key codes, check out http://www.cambiaresearch.com/c4/702b8cd1-e5b0-42e6-83ac-25f0306e3e25/Javascript-Char-Codes-Key-Codes.aspx

Example:

1 comments:

Anonymous said...

Nice!! :D Thx.
Great script. Although those keyboard shortcuts don't work on my IE 7 browser. In FF they do :)