Javascript

Access each character of a string using the charAt() function

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
 
    <script type="text/javascript">
      /**
       * Example showing how to access each character of a string using the charAt() function.
       */
 
      var sVeryLongString = "Hello, world!";
 
      var sEachCharacters = "";
      for(i=0; i<sVeryLongString.length; i++)
      {
        sEachCharacters += sVeryLongString.charAt(i)+"\n";
      }
 
      window.alert(sEachCharacters);
 
    </script>
 
    <title>Access each charater of a string</title>
  </head>
 
  <body>
  </body>
</html>

Add multiple emails in "Invite by E-mail address" input field of Facebook's Events

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
 
    <script type="text/javascript">
 
      /******************************************************************************************************
       * Add multiple emails in "Invite by E-mail address" by injecting html code directly in the input form.
       * This script is to generate the html codes.
       ******************************************************************************************************/
 
      function generateHtmlCodes()
      {
        removeAllChildren('HtmlCodeID'); // Clean the output first.
 
        // Get all commas separated emails addresses.
        var oInputField = document.getElementById('input_field');
        var aEmails = oInputField.value.split(',');
 
        /*
         * For every email, generate html code.
         */
        var sSampleHtml = "<span title=\"xuanngo856\" class=\"removable uiToken\">xuanngo856<input type=\"hidden\" value=\"xuanngo856\" name=\"emails[]\"><input type=\"hidden\" value=\"xuanngo856\" name=\"text_emails[]\"><a href=\"#\" title=\"Remove xuanngo856\" class=\"remove uiCloseButton uiCloseButtonSmall\"></a></span>";
        var sHtml = "";
        for(i=0; i<aEmails.length; i++)
        {
          var sEmail = trim11(aEmails[i]);
          if(sEmail.length > 0)
          {
            sHtml += sSampleHtml.replace(/xuanngo856/g, sEmail);
          }
        }
 
        // Display the generated html code.
        var txtNode = document.createTextNode(sHtml); 
        document.getElementById('HtmlCodeID').appendChild(txtNode);
      }
 
      // Taken from http://blog.stevenlevithan.com/archives/faster-trim-javascript
      function trim11 (str) {
        str = str.replace(/^\s+/, '');
        for (var i = str.length - 1; i >= 0; i--) {
          if (/\S/.test(str.charAt(i))) {
            str = str.substring(0, i + 1);
            break;
          }
        }
        return str;
      }
 
      function removeAllChildren(sElementID)
      {
        var element = document.getElementById(sElementID);
        while (element.firstChild)
        {
          element.removeChild(element.firstChild);
        }   
      }
    </script>
 
 
    <title>Generate html codes to add multiple email addresses</title>
  </head>
 
  <body>
    <h1>Add multiple emails in "Invite by E-mail address" input field of Facebook's Event system by injecting html codes directly in the input form.</h1>
    <h3>This script is to generate the html codes.</h3>
    <p>
      Enter emails(Use commas to seperate emails. e.g. my@email.com, your@mail.com):
      <input type="text" id="input_field" style="width:100%;"/><br />
      <button onclick="generateHtmlCodes()">Generate</button>
      <pre id="HtmlCodeID" style="background-color: #C0C0C0; white-space: -moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; white-space: pre-wrap; word-wrap: break-word;" />
    </p>
  </body>
 
</html>
AttachmentSize
HTML icon InviteByEmails.html2.96 KB

Class

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
 
    <script type="text/javascript">
 
      /**
       * Here is a way to create class in Javascript. There are many other ways.
       * Note: I explicitly omit to show private members as it is getting complicated.
       *        For simplicity, stick with the public members. 
       *        For more info, see http://javascript.crockford.com/private.html
       */
 
      // Employee class
      function Employee(sName)
      {
        // Public variables.
        this.name = sName;
        this.iWorkHours = 5;
      }
 
      // Implementation of functions.
      Employee.prototype.addWorkHours = function(iHours)
      {
        this.iWorkHours += iHours;
      }
 
      Employee.prototype.getWorkHours = function()
      {
        return this.iWorkHours;
      }
 
      // Create Employee object.
      var emplA = new Employee();
 
      // Direct access to public variable.
      emplA.name="Xuan Ngo";
 
      // Calling function.
      emplA.addWorkHours(10);
 
      // Display the results.
      window.alert(emplA.name+ ' worked for ' +emplA.getWorkHours()+ ' hrs.');
    </script>
 
    <title>Class example</title>
  </head>
 
  <body>
  </body>
</html>

http://www.phpied.com/3-ways-to-define-a-javascript-class/

Internet Explorer unknown runtime error with element.innerHTML

Don't use element.innerHTML to add HTML string to an element. It will cause Unknown Runtime Error from Internet Explorer. However, other browsers(e.g. Firefox, Chrome) don't complain about that and work properly. Instead, use the following function to create the complete structure:

  • document.createElement()
  • document.createTextNode()
  • element.appendChild()

Namespace and class

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
 
    <script type="text/javascript">
 
      var MyNamespace = {}; // Create a namespace.
      MyNamespace.NumberOfEmployees = 0; // Global variable of the namespace.
 
      // Employee class
      MyNamespace.Employee = function(sName)
      {
        this.name = sName;
        this.iWorkHours = 5;
 
        MyNamespace.NumberOfEmployees++; // Show the use of global variable of the namespace.
      };
 
      // Implementation of functions.
      MyNamespace.Employee.prototype.addWorkHours = function(iHours)
      {
        this.iWorkHours += iHours;
      };
 
      MyNamespace.Employee.prototype.getWorkHours = function()
      {
        return this.iWorkHours;
      };
 
      // Create Employee objects.
      var emplA = new MyNamespace.Employee();
      var emplB = new MyNamespace.Employee('John Smith');
 
      // Access public variable.
      emplA.name="Xuan Ngo";
 
      // Calling function.
      emplA.addWorkHours(10);
      emplB.addWorkHours(30);
 
      window.alert( emplA.name+ ' worked for ' +emplA.getWorkHours()+ " hrs.\n"+
                    emplB.name+ ' worked for ' +emplB.getWorkHours()+ " hrs.\n"+
                    'There are ' + MyNamespace.NumberOfEmployees + ' employees.'
                    );
 
    </script>
 
    <title>Namespace and class example</title>
  </head>
 
  <body>
  </body>
</html>

Programmatically create JSON structure using javascript

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
 
    <script type="text/javascript">
 
      /*********************************************************
       Programmatically create JSON structure using javascript.
       *********************************************************/
      function displayResults()
      {
        // Define root node.
        var jsonData = {
                          "id": "root",
                          "name": "I'm the parent.",
                          "data": {"someKey": "some Value"}
                        };
 
        // Add children and grand-children.
        jsonData.children=[];
        for(i=0; i<2; i++)
        {
          // Add children.
          jsonData.children[i] = { id: 'ID_'+i, name: 'child_'+i, data: {someKey: 'some Value'} };
 
          // Add grandChildren.
          jsonData.children[i].grandChildren=[];
          for(j=0; j<4; j++)
          {
            jsonData.children[i].grandChildren[j] = { id: 'ID_'+i+'_'+j, name: 'grand-child_'+i+'_'+j, data: {someKey: 'some Value'} };
          }
        }
 
        sResults = JSON.stringify(jsonData, null, 2); // Beautify JSON data structure.
        // Display results.
        var txtNode = document.createTextNode(sResults); 
        document.getElementById('ResultTextID').appendChild(txtNode);
      }
 
    </script>
 
    <title>JSON example</title>
  </head>
 
  <body onload="displayResults()">
    <pre id="ResultTextID" style="background-color: #C0C0C0; word-wrap: break-word;" />
  </body>
</html>

Output:

{
  "id": "root",
  "name": "I'm the parent.",
  "data": {
    "someKey": "some Value"
  },
  "children": [
    {
      "id": "ID_0",
      "name": "child_0",
      "data": {
        "someKey": "some Value"
      },
      "grandChildren": [
        {
          "id": "ID_0_0",
          "name": "grand-child_0_0",
          "data": {
            "someKey": "some Value"
          }
        },
        {
          "id": "ID_0_1",
          "name": "grand-child_0_1",
          "data": {
            "someKey": "some Value"
          }
        },
        {
          "id": "ID_0_2",
          "name": "grand-child_0_2",
          "data": {
            "someKey": "some Value"
          }
        },
        {
          "id": "ID_0_3",
          "name": "grand-child_0_3",
          "data": {
            "someKey": "some Value"
          }
        }
      ]
    },
    {
      "id": "ID_1",
      "name": "child_1",
      "data": {
        "someKey": "some Value"
      },
      "grandChildren": [
        {
          "id": "ID_1_0",
          "name": "grand-child_1_0",
          "data": {
            "someKey": "some Value"
          }
        },
        {
          "id": "ID_1_1",
          "name": "grand-child_1_1",
          "data": {
            "someKey": "some Value"
          }
        },
        {
          "id": "ID_1_2",
          "name": "grand-child_1_2",
          "data": {
            "someKey": "some Value"
          }
        },
        {
          "id": "ID_1_3",
          "name": "grand-child_1_3",
          "data": {
            "someKey": "some Value"
          }
        }
      ]
    }
  ]
}

Remove element by tag name

function removeElementByTagName(tagName)
{
    var element = document.getElementsByTagName(tagName);
    for (index = element.length - 1; index >= 0; index--)
    {
        element[index].parentNode.removeChild(element[index]);
    }
}

Simulate pressing a key

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
 
    <script type="text/javascript">
      /*************************************************
       * Example showing how to simulate pressing a key.
       *************************************************/
 
      function pressChar(char)
      {
        try
        {
          // Create the key press event.
          var pressEvent = document.createEvent('KeyboardEvent');
          pressEvent.initKeyEvent("keypress", true, true, window, 
                                    false, false, false, false, 
                                    0, char.charCodeAt(0));
 
          var input = document.getElementById('input_field'); // Get the element where you want to press.
 
          input.dispatchEvent(pressEvent); // Press the key.
        }
        catch (e) {
            alert ("Your browser does not support this example!");
        }
      }
    </script>
 
 
    <title>Simulate pressing a key</title>
  </head>
 
  <body>
    <button onclick="pressChar('s')">Simulate pressing the 's' key in the input field.</button>
    <input type="text" id="input_field" />
  </body>
 
</html>

Sort multidimensional array

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
<html>                                                                 
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script type="text/javascript">
    //<![CDATA[
      //========================================================
      // Example showing how to sort multi-dimensional arrays.
      //========================================================
 
      var persons = [
              // First    , Last    , Age
              ["John"     , "Smith" , 29],
              ["Nicole"   , "Kidman", 46],
              ["Elizabeth", "Taylor", 79],
              ["Halle"    , "Berry" , 46],
              ["Liz"      , "Smith" , 29]
                   ]; 
 
      function main()
      {
        // Show the initial values.
        create_rows_from_array(persons, "initial-values-body");
 
        // Sort by last name
        persons.sort(sort_by_last_name);
        create_rows_from_array(persons, "sort-by-last-name-body");
 
        // Sort by last name and first name.
        persons.sort(sort_by_last_first_name);
        create_rows_from_array(persons, "sort-by-last-first-name-body");
 
      }
 
 
      //================================
      // Sort functions
      //================================
      // Sort by last name in ascending order.
      function sort_by_last_name(personA, personB)
      {
        var x = personA[1]; // Last name index is 1.
        var y = personB[1];
 
        if( x < y )
          return -1;
        else if ( x > y )
          return 1;
        else
          return 0;       
      }
 
      //Sort by last name and first name in ascending order.
      function sort_by_last_first_name(personA, personB)
      {
        // Append last name and first name together.
        //  And, then, compare the combined string.
        var x = personA[1]+personA[0]; 
        var y = personB[1]+personA[0];
 
        if( x < y )
          return -1;
        else if ( x > y )
          return 1;
        else
          return 0;       
      }
 
      //=====================================================
      // Help function. Not relevant to learn how to sort.
      //=====================================================
      function create_rows_from_array(data, table_id)
      {
        var table = document.getElementById(table_id);
        for(i=0; i<data.length; i++)
        {
          var row = document.createElement("tr");
          for(j=0; j<data[i].length; j++)
          {
            var td = document.createElement("td");
            var node = document.createTextNode(data[i][j]);
            td.appendChild(node);
 
            row.appendChild(td);
          }
          table.appendChild(row);
        }
 
      }              
    //]]>
    </script>
  </head>                                                                 
  <body onload="main()">
 
  <h1>Initial values</h1>
  <table>
    <thead>
      <tr>
        <th>First name</th>
        <th>Last name</th>
        <th>Age</th>
      </tr>
    </thead>  
    <tbody id="initial-values-body"/>
  </table>    
 
  <br /><br />
  <!-- Sort by last name -->
  <h1>Sort by last name</h1>
  <table>
    <thead>
      <tr>
        <th>First name</th>
        <th>Last name</th>
        <th>Age</th>
      </tr>
    </thead>  
    <tbody id="sort-by-last-name-body"/>
  </table>      
 
  <br /><br />
  <!-- Sort by last name and first name -->
  <h1>Sort by last name and first name</h1>
  <table>
    <thead>
      <tr>
        <th>First name</th>
        <th>Last name</th>
        <th>Age</th>
      </tr>
    </thead>  
    <tbody id="sort-by-last-first-name-body"/>
  </table>  
 
</body>                                                                 
</html>