TwitterFacebookGoogle

Dynamically creating input fields on tab via CoffeeScript and JQuery

Below is my very own, very first, super-clean, super-sexy CoffeeScript snippet that dynamically appends input fields as the user tabs through the current input field. The source-code is on the left. On the right you can actually play with it and see it in action!

inputId = 1;
 
jQuery -> 
  $("#fields :input").live 'keydown', (e) ->
    if isModifierKeyPressed e
      return 
 
    if e.keyCode in [9, 13]
      e.preventDefault
 
      if isLastActivity($(this).attr 'id')
	addAnotherTextInput();
 
      $(this).next().focus();
      return false
 
isModifierKeyPressed = (e) ->
  e.ctrlKey or e.altKey or e.shiftKey
 
isLastActivity = (inputFieldId) ->
  inputNumber = 
    (Number) inputFieldId.split('activity')[1]
  inputNumber == inputId
 
addAnotherTextInput = ->
  inputId++
  $("#fields").append getInputField inputId
 
getInputField = (inputId) ->
  return "<input type='text' id='activity#{inputId}' 
                 class='input-super-large' 
                 placeholder='Type something and then press tab' />"
Twitter Email Linkedin Digg Stumbleupon Subscribe

Unobtrusive JavaScript with HTML 5

HTML 5 supports a new feature known as Custom Data Attributes. These attributes give us the ability to define custom attributes for ANY HTML tags. The only restriction is that the tag must start with "data-". For instance, we can add a custom attribute to a link as follows:
  <a href="#" data-search-by-type="<value>">My link with custom attribute</a>
This feature comes with a neat benefit that we no longer need ANY inline javascript inside our HTML content. For instance, say, we've got a commonly-used javascript function that performs a search by searchType:
function search(var searchType)
{
   ...
   ...
}
Prior to HTML 5, we would invoke the function using inline javascript inside our HTML tags:
<a href="javascript:search('byName')" class='search-link'>Search By Name</a>  
<a href="javascript:search('byType')" class='search-link'>Search By Type</a>
With the introduction of Custom Data Attributes, we can now completely do away with the in-line javascript and write the links as follows:
<a href="#" data-search-by='byName' class='search-link'>Search By Name</a>
<a href="#" data-search-by='byType' class='search-link'>Search By Type</a>
We would then add the following to our common.js file that contains the search() function:
$(document).ready(function() {
  $(".search-link").click(function () { search(this.getAttribute("data-search-by")); })
})
The Custom Data Attributes in HTML 5 gives us a benefit that is similar in nature to the benefits provided by the CSS model - namely, separations of concerns. CSS enables us to separate content from the presentation of that content, thus enabling our HTML pages to follow a well-defined structure. Similarly, with Custom Data Attributes we can now separate logic or functionality from HTML content. This provides with the following benefits:
  1. We no longer need to pollute our HTML with in-line Javascript.
  2. Keeping all our Javascript functionality centralized makes it much easier to manage.
  3. The use of Custom Data Attributes increases code re-usability since they can effectively serve as parameters to our javascript functions.
Twitter Email Linkedin Digg Stumbleupon Subscribe

JQuery snippet to detect keystrokes on the numeric key-pad.

The below JQuery snippet returns the character corresponding to the key that was pressed on the QWERTY keyboard or the numeric key-pad. For instance, pressing the '1' key will return the text '1'. Similarly, pressing the '+' key will return back the text '+'.
$(document).keydown(function (event) {
      toCharacter(event.keyCode);
 });
 
function toCharacter(keyCode) {
 
    // delta to convert num-pad key codes to QWERTY codes.
    var numPadToKeyPadDelta = 48;
 
    // if a numeric key on the num pad was pressed.
    if (keyCode >= 96 && keyCode <= 105) {
        keyCode = keyCode - numPadToKeyPadDelta;
        return String.fromCharCode(keyCode);
    }
 
    if (keyCode == 106)
        return "*";
 
    if (keyCode == 107)
        return "+";
 
    if (keyCode == 109)
        return "-";
 
    if (keyCode == 110)
        return ".";
 
    if (keyCode == 111)
        return "/";
 
    // the 'Enter' key was pressed
    if (keyCode == 13)
        return "=";  //TODO: you should change this to interpret the 'Enter' key as needed by your app.
 
    return String.fromCharCode(keyCode);
}

A little explanation is probably in order...


Javascript provides the
String.fromCharCode()
method that converts an ASCII character code into it's equivalent text value. For instance,
String.fromCharCode(65)
returns the character 'A'. The method works great until to try to use it for keys that live on the numeric keypad. The ASCII code for the '1' key on the numeric key pad is 97. If you look this up on the ASCII Table, you will find that the ASCII code 97 corresponds to the character 'a' and not the character '1' denoted on the numeric key pad! The reason for this, as far I can tell, is that the numeric keys simply overload on the existing the ASCII codes. A little calculation will reveal that subtracting 48 from the ASCII code of the numeric keys will give us the "correct" ASCII code. For instance, subtracting 97 (which is the ASCII code for the '1' key on the numeric keypad) from 48 gives us 49. Look up the ASCII code 49 on the ASCII Table and you will find that it maps to the character '1'! For the keys that correspond to the various symbols such as '+', '-', etc., I am simply returning back the corresponding character. No mystery there. Hope this helps!
Twitter Email Linkedin Digg Stumbleupon Subscribe
CyberChimps