Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

2/1/11

JavaScript encodeURI and encodeURIComponent

ASCII Char Comparisons
#    CH  EU     EUC  NOTES
32       %20    %20  space char
96   `   %60    %60
33   !   !      !
64   @   @      %40  x
35   #   #      %23  x
36   $   $      %24  x
37   %   %25    %25
94   ^   %5E    %5E
38   &   &      %26  x
42   *   *      *
40   (   (      (
41   )   )      )
45   -   -      -
61   =   =      %3D  x
91   [   %5B    %5B
93   ]   %5D    %5D
92   \   %5C    %5C
59   ;   ;      %3B  x
39   '   '      '
44   ,   ,      %2C  x
46   .   .      .
47   /   /      %2F  x
126  ~   ~      ~
95   _   _      _
43   +   +      %2B  x
123  {   %7B    %7B
125  }   %7D    %7D
124  |   %7C    %7C
58   :   :      %3A  x
34   "   %22    %22
60   <   %3C    %3C
62   >   %3E    %3E
63   ?   ?      %3F  x

LEGEND
#   ascii code
CH  char
EU  encodeURI
EUC encodeURIComponent
x   diffs

List Chars using jQuery map()
//escape char: \
chars = " `!@#$%^&*()-=[]\\;',./~_+{}|:\"<>?"
jQuery.map(chars.split(""),
  function(c) {
    console.log(c.charCodeAt(0) + " " + c + "  " + encodeURI(c) + "  " + encodeURIComponent(c));
  })

1/29/11

JavaScript Dates

Dates contain the number of milliseconds since 1-1-1970 00:00:00 UTC.

Date Constructor
new Date()  //returns current datetime
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day [, hour, minute, second, millisecond])  //optional time-params default to 0

Params: milliseconds ms since 1-1-1970 00:00:00 UTC
        dateString   string format
        year         4 digit year
        month        0-11
        day          1-31  day of the month
        hour         0-23  hour of the day
        minute       0-59  minute segment of a time reading
        second       0-59  second segment of a time reading
        millisecond  0-999 ms segment of a time reading

Static Methods
These methods return the milliseconds since 1-1-1970
Date.now()  //use for timestamps & unique IDs, todo: minimum 15 millisecond resolution on windows?
Date.parse(datestring)
Date.UTC(year, month [, date, hrs, min, sec, ms])  //universal time

d = new Date("Jan 7, 2011")               //Fri Jan 07 2011 00:00:00 GMT-0700 (Mountain Standard Time)
d.getMonth()                              //0 (0-11)
d.getDay()                                //5 (0-6) friday
d.getDate()                               //7 (1-31)
d.getFullYear()                           //2011
d.getHours()                              //0

d = new Date("Jan 07 2011 01:02:03")      //Fri Jan 07 2011 01:02:03 GMT-0700 (Mountain Standard Time)
d.getHours()                              //1
d.getMinutes()                            //2
d.getSeconds()                            //3

d = new Date("Jan 07 2011 01:02:03:456")  //Fri Jan 07 2011 01:02:03 GMT-0700 (Mountain Standard Time)
d = new Date(2011, 0, 7, 1, 2, 3, 456)
d.getMilliseconds()                       //456
d.getTime()                               //1294387323456 milliseconds since 1-1-1970
Date.parse("01-07-2011 01:02:03:456")     //1294387323456 milliseconds since 1-1-1970
Date.UTC(2011, 0, 7, 1, 2, 3, 456)        //1294362123456

formatDate(d)                             //"1-7-2011"
formatDatePad(d)                          //"01-07-2011"
formatDateTime(d)                         //"1-7-2011 1:2:3:456"
formatDateTime(addMinutes(d, 60))         //"1-7-2011 2:2:3:456"
formatDateTime(addMinutes(d, 10))         //"1-7-2011 1:12:3:456"
formatDateTime(addMinutes(d, 1440))       //"1-8-2011 1:2:3:456"

//debug
console.log(d.getMonth());console.log(d.getDate());console.log(d.getFullYear());console.log(d.getHours());console.log(d.getMinutes());console.log(d.getSeconds());console.log(d.getMilliseconds())

//equivalent date constructors, exclude times for date only, string formats can be used with Date.parse()
new Date("01-07-2011 01:02:03")
new Date(2011, 0, 7, 1, 2, 3)
new Date("Jan 07 2011 01:02:03")
new Date("Fri Jan 7 2011 1:2:3")
new Date("Fri Jan 07 2011 01:02:03 GMT-0700")

//-------------
function addMinutes(date, minutes){  //returns date
  var result = new Date(date.getTime());
  result.setMinutes(result.getMinutes() + parseInt(minutes));
  return result;
}

function formatDate(date){  //returns string
  return (date.getMonth() + 1) + "-" + date.getDate() + "-" + date.getFullYear();
}

function formatDatePad(date){  //returns string
  return (pad2(date.getMonth() + 1)) + "-" + pad2(date.getDate()) + "-" + pad2(date.getFullYear());
}

function formatDateTime(date){  //returns string
  return (date.getMonth() + 1) + "-" + date.getDate() + "-" + date.getFullYear() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds() + ":" + date.getMilliseconds();
}

//http://www.electrictoolbox.com/pad-number-two-digits-javascript/
function pad2(number){  //returns string
  return (number < 10 ? "0" : "") + number;
}

Conversions
INTERVAL       MS   SECS  MINS   HOURS
1 sec        1000      1  1/60  1/3600
1 min       60000     60     1    1/60
10 min     600000    600    10   10/60
1 hour    3600000   3600    60       1
1 day    86400000  86400  1440      24  ms=24*60*60*1000

1/12/11

Using External JavaScript Files with Google Analytics

For basic page tracking, put the code in an external file.

Then you can use this
<script src="/js/googleAnalytics.js" type="text/javascript"></script>

instead of
<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXX-X']);
  _gaq.push(['_trackPageview']);
  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
</script>

Add to files, right before the closing head tag.


googleAnalytics.js
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXX-X']);
_gaq.push(['_trackPageview']);
(function() {
  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

3/15/10

JavaScript Namespaces

Two variations for implementing JavaScript namespaces.
The abc namespace syntax is the simplest and useful when only public members are being wrapped.
The xyz namespace syntax can be used for public and private members.
var abc =
{
  version: '1.0',
  foo: function()
  {
    return 'abc.foo';
  }
};

var xyz = function()
{
  //private
  var _version = '2.0';
  function _foo()
  {
    return 'xyz.foo';
  }

  //public
  return {
    version: _version,  //access private var
    foo: function()
    {
      return _foo();  //access private fx
    },
    bar: function(text)
    {
      return 'xyz.bar ' + text;
    }
  };
}();  //self invoking fx

Examples
abc.foo();
abc.version;

xyz.foo();
xyz.bar('test');
xyz.version;

//output
abc.foo
1.0

xyz.foo
xyz.bar test
2.0

Object Graphs in Firebug Watch Window

A slightly modified version showing sub namespaces, eg abc.demo.foo()
var abc = {};
abc.demo =
{
  version: '1.1',
  foo: function()
  {
    return 'abc.demo.foo';
  }
};

var xyz = {};
xyz.demo = function()
{
  //private
  var _version = '2.1';
  function _foo()
  {
    return 'xyz.demo.foo';
  }

  //public
  return {
    version: _version,  //access private var
    foo: function()
    {
      return _foo();  //access private fx
    },
    bar: function(text)
    {
      return 'xyz.demo.bar ' + text;
    }
  };
}();  //self invoking fx

If you use libraries with nested namespaces, local references improve performance by minimizing member lookup.
var abcd = abc.demo;
abcd.foo();
abcd.version;

1/31/10

jQuery Template Page

This page can be used for quick-start jQuery development.
jQuery v1.4.x is loaded from the Google AJAX Libraries API site.
Page caching is disabled via meta tags to make it easy to test changes.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery Template</title>
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="-1" />
<style type="text/css">body,input,button{font-family:Verdana,Sans-Serif;font-size:.9em;}</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
  //$(document).ready(function(){alert('DOM ready');});
  //$(document).ready(f1);
  function f1()
  {
    alert('f1() - DOM ready');
  }

  function f2()
  {
    var input = $.trim($("#input1").val());
    $("#label1").text(input);
  }
</script>
</head>
<body>
  <!--form & submit button allows user to submit by pressing enter key 
    while input text box has focus - instead of having to manually click 
    button or tabbing to button and pressing space key-->
  <form action="">
    <label id="label1">label1</label><br />
    <input id="input1" type="text" maxlength="32" title="input" /><br />
    <input type="submit" />
  </form>
  
  <script type="text/javascript">
    $("form").submit(function(){f2(); return false;});
  </script>
</body>
</html>

11/27/09

YUI Compressor for JavaScript and CSS

The YUI Compressor can be used to compress JavaScript and CSS files. It also offers a low-security JavaScript obfuscation option via local symbol renaming - it does not rename functions.

The tool requires the Java SDK 1.4 or later and can be run from the command line. The command line is useful because formatted, commented JavaScript can be used for development and compressed versions can be easily generated for test and prod.

To avoid compression build errors, verify your file text encoding. For Visual Studio UTF-8, make sure to select the "Unicode UTF-8 without signature" encoding from the File - Advanced Save Options menu. Then include the charset UTF-8 option in the command.

Example - run as one line
java -jar c:\lib\yui\yuicompressor-2.4.2.jar
c:\code\web\scripts\file.js
-o c:\code\web\scripts\file.min.js
--charset utf-8