Tuesday, December 04, 2007

Free Alternatives to Adobe Reader

As the years have gone by, Adobe Reader (formally Adobe Acrobat Reader) has got bigger (version 5.05 is 8.6MB and will probably still handle many PDF's OK, the latest, 8.1.1 is 22.3MB) and invariably slower with each release. Thankfully there are free alternatives, that are both a smaller download and much faster at opening PDF's.

  • SumatraPDF (< 1MB, still in beta, open source)
  • Foxit Reader (around 2MB download)
  • PDF XChange Viewer (13MB, but still smaller than Adobe Reader and supports comments/annotations, filling in forms and exporting text and images)

Alternatively, you could still have Adobe Reader, and use a tool that disables the plugins that slow the startup - e.g. Adobe Reader SpeedUp or PDF SpeedUp (although I haven't tested either of these).

Monday, December 03, 2007

Analyse performance of web pages with YSlow

YSlow is a plugin for Firefox developed by Yahoo that analyses your web pages and reports back on any performance issues (plus gives a grade). There is a performance report (which shows you areas which can be improved), stats (overview of what is loaded, cached/uncached, cookies and number of HTTP requests), components (page, CSS/JS,JPG etc - expiry, if gzip used, response time, ETag and file sizes) and various tools (view all CSS/JavaScript and a JSLint report).

This plugin depends on Firebug.

Tuesday, November 27, 2007

Form Layout Using CSS

I have created a sample for laying out fields within a fieldset (so that the labels are all lined up) - I use a fieldset as they are handy for grouping related fields together. Nothing too fancy, but it can be used as a basic for something better. Works with Internet Explorer 6 and 7, Firefox 2 and Opera 9.02.

Clearing tempororary files

Being a laptop user, disk space can be an issue and temporary files can be one of the things to clear out to free up some space. There are freeware applications that enable you do do this, but you can just use what is built into Windows to do the same thing. It is run from the command line and is the command rd or rmdir, which basically means 'remove directory'. It can be used to remove directories as well as its sub directories and files, by just typing rd C:\MyFolder\ /s /q (the /s switch is to include sub directories and /q prevents the prompt to remove a directory tree).

At first, I thought that running it on the temporary folders directory would remove it and somehow break windows, but it doesn't. This is because there are files within that directory that are in use, and as a result, it can't be deleted. However, all the files and sub directories that aren't locked are removed, freeing up space. I use a simple batch file that cleans up the temporary folders, which can be set to run as a scheduled task (assuming you have the computer on at the time).


@echo off
rem clean up windows temp directory
rd C:\Windows\Temp\ /s /q
rem clean up users temp directory
rd %temp% /s /q

The advantage of doing it in a batch file is that you can easily add any directories that also have temporary files, for instance, to clean up you Internet Explorer temporary files add in rd "%homepath%\Local Settings\Temporary Internet Files\" /s /q (assuming you haven't moved the location of the temporary internet files folder).

You can also use the Disk Cleanup tool that is built into Windows: Right Click desired drive in 'My Computer', select 'Properties', then click the 'Disk Cleanup' button. This also compresses files that you don't access often, but takes some time.

Friday, September 28, 2007

Sorting Files by Name, Date, FileSize etc (C#)

It is simple to get a list of files in .NET, you simply do:

string folder = "c:\\windows\\";
string[] files = Directory.GetFiles(folder);

This will get all the files in C:\Windows (does not include subdirectories). However, they are sorted by name (A-Z) and there aren't any options in the GetFiles method to return them in any other order. Luckily, the results are returned as an array and they can be sorted with a custom comparer. I have created a FileComparer class that can be used to sort the files (works in both .NET 1.1 and 2.0):

public class FileComparer : IComparer
 public enum CompareBy
  Name /* a-z */,
  LastWriteTime /* oldest to newest */,
  CreationTime  /* oldest to newest */,
  LastAccessTime /* oldest to newest */,
  FileSize /* smallest first */
 // default comparison
 int _CompareBy = (int)CompareBy.Name;
 public FileComparer()
 public FileComparer(CompareBy compareBy)
  _CompareBy = (int)compareBy;
 int IComparer.Compare( object x, object y )
  int output = 0;
  FileInfo file1 = new FileInfo(x.ToString());
  FileInfo file2 = new FileInfo(y.ToString());
   case (int)CompareBy.LastWriteTime:
    output = DateTime.Compare(file1.LastWriteTime, file2.LastWriteTime);
   case (int)CompareBy.CreationTime:
    output = DateTime.Compare(file1.CreationTime, file2.CreationTime);
   case (int)CompareBy.LastAccessTime:
    output = DateTime.Compare(file1.LastAccessTime, file2.LastAccessTime);
   case (int)CompareBy.FileSize:
    output = Convert.ToInt32(file1.Length - file2.Length);
   case (int)CompareBy.Name:
    output = (new CaseInsensitiveComparer()).Compare( file1.Name, file2.Name );
  return output;

To use it is fairly simple:

string folder = "c:\\windows\\";
string[] files = Directory.GetFiles(folder);
IComparer comp = new FileComparer(FileComparer.CompareBy.FileSize);
Array.Sort(files, comp);
foreach(string file in files)

This will output a list of files in the C:\Windows directory, sorted smallest to largest. If you want it the other way round, just call Array.Reverse(files) after the sort.

Tuesday, September 18, 2007

Google Code uses jQuery

Google Code is now another high profile site that uses jQuery. It is used to show Google Code Blog posts, featured projects and Google Tech Talks on the home page. It doesn't use jQuery's AJAX functionality to get the feeds though.

Wednesday, September 12, 2007

Select box manipulation with jQuery - new plugin: selectedValues

A new plugin has been added for getting the values of options selected in a select box. More details and download from the Select Box Manipulation project page at the jQuery site.

Friday, September 07, 2007

CssCompact: A WebHandler for shrinking CSS files (ASP.NET)

Update (20 Feb 2010): Static regular expression, compiled (performance improvement, but will be negligible for low volume sites). See Compacting CSS on-the-fly for an HttpHandler based on this.

Update (08 July 2009): Check file extension is CSS.

CssCompact is a simple WebHandler for sending smaller CSS files to the client. It simply removes linebreaks, tabs, spaces (before CSS properties) and comments. That way you can still have your commented CSS code, and also save bandwidth.

Use is simple, just pass on the stylesheet as a parameter when loading your stylesheet:

Add to <head>:

<link rel="stylesheet" type="text/css" href="/style/CssCompact.ashx?stylesheet=/style/style.css" />


<style type="text/css"> @import "/style/CssCompact.ashx?stylesheet=/style/style.css"; </style>

Create CssCompact.ashx:

<%@ WebHandler Language="C#" Class="CssCompact" %>

using System;
using System.Web;
using System.IO;
using System.Text.RegularExpressions;

public class CssCompact : IHttpHandler
 // remove linebreaks, whitespace and comments
 private static RemoveRegex = new Regex(@"^\s+|/\*([^*\\\\]|\*(?!/))+\*/|\r|\n|\t", RegexOptions.Multiline | RegexOptions.Compiled);
 public void ProcessRequest(HttpContext c)
  string stylesheet = c.Request.QueryString["stylesheet"];
  c.Response.ContentType = "text/css";
  if (stylesheet != null)
   string filename = c.Server.MapPath(stylesheet);
   FileInfo f = new FileInfo(filename);
   if(f.Extension == ".css" && f.Exists)
    c.Response.AddHeader("Last-Modified", f.LastWriteTime.ToString("U"));
    c.Response.Expires = 0;
    if(c.Request.HttpMethod != "HEAD")
     using (StreamReader cssStream = f.OpenText())
      string cssContent = cssStream.ReadToEnd();
      cssContent = RemoveRegex.Replace(cssContent, "");
  c.Response.Write("/* No valid style sheet selected */");

 public bool IsReusable
   return false;


Friday, August 31, 2007

Post update - Windows Scripting: Adding/removing network printers and drives

Windows Scripting: Adding/removing network printers and drives has been updated to show you how to add entries to the event log in case of an error, rather than show a message box.

Thursday, August 30, 2007

The JavaScript CompressorRater

The JavaScript CompressorRater compares several popular tools used for compressing JavaScript. At the moment, it compares JSMin, Dojo shrinksafe, Packer and the YUI Compressor (which has been recently been released and has very good results so far). Dojo shrinksafe and YUI Compressor require Java and Rhino installing. Packer can be run online and JSMin is a command line tool (with code available in several languages for use within your own applications).

Before using any of these tools, it is best to check your syntax is correct (adding the optional semi-colons and checking the code with JSLint).

You can see the results of the compression with several popular JavaScript libraries: jQuery, Prototype, YUI and Scriptaculous. Mootools and Dojo are missing from the comparison. Rather than using one tool to compress your code, it may be better to try several and use the one that gives you the best results.

Friday, August 24, 2007

New Version of jQuery - 1.1.4

A new version (1.1.4) of jQuery has been released - jQuery 1.1.4: Faster, More Tests, Ready for 1.2. There are several notable features in this release:

  • Any name jQuery - so you can use multiple versions of jQuery on the same page (though I wouldn't recommend that if at all possible) - e.g. myobj.jQuery = jQuery.noConflict(true)
  • It is also faster (yet again) - although it is only slow if you call the same query a lot (hundreds) of times (e.g. $("#myel").foo(); $("#myel").bar(); ... instead of $myel = $("#myid"); $myel.foo(); $myel.bar(); ...
  • New features: .slice() (works like the JavaScript array method slice), :has() (select element only if it has (an)other element(s) in it), recursive .extend() and .noConflict(true) (see first point)
  • Deprecated methods are also detailed in the blog post - i.e. they won't be in jQuery 1.2, with one exception, XPath attribute selector (deprecated in 1.1.4 and 1.2 - $("div[@attr]"))

Monday, August 20, 2007

jQuery Cheat Sheet (Excel and Google Spreadsheet)

A cheat sheet for jQuery has recently been created by Matt Kruse and posted on the jQuery discussion list. It is available in Excel format via jQuery Tips (JavaScript Toolbox) or in Google Spreadsheet format (the Excel sheet created by Matt was converted into this format by George Blouin). Being in a spreadsheet format means it is easily editable, to add your own 'cheats'.

Friday, July 27, 2007

Select box manipulation with jQuery - update to removeOption

The previous update to this collection of plugins introduced a cache when adding options (i.e. made it much faster if adding a lot of options). However, it was not cleared when remove options (causing possible conflicts). This is now done and an extra parameter has been added to removeOption (of boolean type), that when set to true, will only remove options if it matches any option(s) defined by the first parameter. More details and download from the Select Box Manipulation project page at the jQuery site. A demo is also available.

Thursday, July 12, 2007

FileHelpers - a library for worked with CSV files (.NET)

Best described in the words on the FileHelpers website:

The FileHelpers are a free and easy to use .NET library to import/export data from fixed length or delimited records in files, strings or streams.

It is a library that can be used to work with flat text files (e.g. Comma Separated Value (CSV) or Tab Separated Values (TSV) etc). Available for commercial and non-commercial use (under the LGPL). They also have a blog.

There is also a CSV parser on CodeProject if you can't use a library licensed under the LGPL: A Fast CSV Reader. Not as powerful as FileHelpers but still good nonetheless.

Wednesday, July 11, 2007

Text Clips for Programmers Notepad 2 (jQuery)

I have not updated my jQuery Text Clips for Programmer's Notepad 2 for a while (since 1.0.2) so have added them for jQuery 1.1.2 @ Text Clips for Programmer's Notepad 2 (generated using the jQuery Text Clip Generator).

Thursday, July 05, 2007

Sending emails with C#

I'm sure many may already know how to do this, but for those that don't, sending an email using .NET is very easy and can be used in ASP.NET as well as Windows Forms or Console applications (assuming you have CDOSYS installed). This example also shows how to send an email to multiple recipients (requires you to import the namespace System.Collections).

.NET 1.0 / 1.1 (import the namespace System.Web.Mail)
MailMessage m;
SmtpMail.SmtpServer = "smtpservername";
ArrayList recipients = new ArrayList();
for (int i = 0;i < recipients.Count;i++)
 m = new MailMessage();
 m.To = recipients[i].ToString();
 m.From = "me@mysite.com";
 m.BodyFormat = MailFormat.Html;
 m.Subject = "Subject of the email";
 m.Body = String.Format(
  "<p style='font: 12px Arial'>Sending email to {0}</p>",
.NET 2.0+ (import the namespace System.Net.Mail)
MailMessage m;
SmtpClient smtp = new SmtpClient("smtpservername");
ArrayList recipients = new ArrayList();
for (int i = 0;i < recipients.Count;i++)
 m = new MailMessage();
 m.To = recipients[i].ToString();
 m.From = "me@mysite.com";
 m.IsBodyHtml = true;
 m.Subject = "Subject of the email";
 m.Body = String.Format(
  "<p style='font: 12px Arial'>Sending email to {0}</p>",

Friday, June 15, 2007

Windows Scripting: Adding/removing network printers and drives

While I normally make posts related to web development, I may occasionally post something that isn't used in web development, but still has some kind of relationship (normally the underlying technology used) - for example: VBScript - Set Homepage (MSIE) / Add Notepad to Send To.

In this case, it is VB Scripting and is an example of how to perform several common tasks (related to printers and drives) that network/server administrators may want to do, through a simple script (could be via login script, or executed directly on the client) rather than using the Windows GUI. It also demonstrates how to do basic error handling. Just take the following code (tweak as needed) and paste it in a script file (e.g. login.vbs). Only been tested in Windows XP (for Windows 98, you have to also define the driver name as a second parameter for AddWindowsPrinterConnection, it should work as is in Windows 2000).

Option Explicit
Dim WSHNetwork 
Dim WSHShell

On Error Resume Next

Set WSHNetwork = CreateObject("WScript.Network")
Set WSHShell = CreateObject("WScript.Shell")

rem Add a printer
WSHNetwork.AddWindowsPrinterConnection "\\HOSTNAME\PrinterShareName"
HandleError "Could Not Add Printer"

rem Set this as the default printer
WSHNetwork.SetDefaultPrinter "\\HOSTNAME\PrinterShareName"
HandleError "Could Not Set As Default Printer"

rem Remove an existing printer
WSHNetwork.RemovePrinterConnection "\\HOSTNAME\RemovePrinterShareName"
HandleError "Could Not Remove Printer / Printer Already Removed"

rem Map a drive
WSHNetwork.MapNetworkDrive "L:", "\\HOSTNAME\ShareName"
HandleError "Could Not Map Drive"

rem Remove a drive
WSHNetwork.RemoveNetworkDrive "M:"
HandleError "Could Not Remove Mapped Drive"

Function HandleError(Title)
 If Err.Number <> 0 Then
  rem Add to event log. First parameter can be:
  rem 0 (SUCCESS), 1 (ERROR), 2 (WARNING)
  WSHShell.LogEvent 1, "Error: " & Title & Chr(13) & "Error Number: " & Err.Number & Chr(13) _
   & "Description: " & Err.Description
 End If
End Function

You can call this from a batch file (e.g. login.cmd)

@echo off
set wsh=no
rem Loop through folders in path and check if cscript.exe exists
for %%p in (%path%) do if exist %%p\cscript.exe set wsh=yes
if %wsh%==no goto wshno
cscript login.vbs
goto finally
echo Windows Scripting Not Installed
rem script has finished

Tuesday, June 05, 2007

Link: HTML Entity Character Lookup

HTML Entity Character Lookup is a useful web based tool for looking up HTML entities codes for characters that you have an idea what they look like (e.g. a 'c'), but not sure what the entity code (e.g &copy; for ©) to use is.

Friday, May 25, 2007

Controlling browser scrollbars

In Firefox, the vertical scrollbar only shows when the page contents do not go beyond the height of the browser window (i.e. you just have a simple 'Hello World' or very little content on your page). On the other hand, the scrollbar always shows if you are using Internet Explorer. For consistency across these (and possibly other browsers as well), you can apply a little bit of CSS.

To make IE behave like Firefox (only show scrollbar when needed), just do this:

html {
   overflow-y: auto;

To always show the scrollbar (to prevent the layout changing when more content-rich pages are loaded on your site):

html {
   overflow-y: scroll;

I also use the same trick to only show scrollbars in <textarea>'s when needed:

textarea {
    overflow: auto;

Tuesday, May 08, 2007

jQuery Plugin: focus fields

focus fields is a plugin for jQuery that adds an outline and background colour to a text input when it is given focus.

Friday, April 27, 2007

jQuery Plugin update: newsticker

I've updated my news ticker plugin to fix a few bugs. Also included on the page are some examples of adding content dynamically and applying it to the added content.

Tuesday, April 17, 2007

jQuery Plugin update: jQIR (jQuery Image Replacement)

jQIR (jQuery Image Replacement) has been updated to take into account hyperlinks (i.e. it wraps the image with them). You can also run a function when the image has loaded.

Thursday, April 05, 2007

Select box manipulation with jQuery - update and new plugin

In my plugins for working with select boxes, ajaxAddOption can now call a function after the options have been added. There is also a new plugin (containsOption) for checking if an option with a given value exists.

Tuesday, March 13, 2007

Iframes and jQuery - Working with an iframe's parent

As I stated in my last post about iframe's and jQuery, the load event was only fired once in Internet Explorer, so this may be a problem in some situations (for instance, when you go to a new page in the iframe (which is the only reason I can think of for using one instead of includes)). You can put the code into the iframe and work with the page that contains it instead. This actually may be more desirable as it is simpler and works in more browsers (Firefox, Internet Explorer, Opera 8.54+ tested)

$( function() {
   var p = parent;
   $("a").click( function() {
       p.$("#myinput").val("Anchor clicked: " + this.href);
       return false;

Iframes and jQuery - Working with an embedded iframe

IFrames, while they can be bad for accessibility (i.e. bookmarking), can also be very handy.

What I found was that working with iframes proved troublesome. I initially thought it would be as simple as this:

$( function() {
 $("#myiframe").load( function(){
  alert("Number of anchors: " + this.$("a").size());
  alert("Document title: " + this.document.title);
<iframe src="myiframe.html" id="myiframe" name="myiframe"></iframe>

However, this caused several errors: this.document has no properties (i.e. this.document is undefined) and this.$ is not a function, so I had to find another way. After some trial and error in Internet Explorer and Firebug in Firefox, I found a way (which also works in Opera 9 as well, unsure about Safari though).

$( function() {
   var myiframe = $($.browser.msie ? frames["myiframe"] : "#myiframe");
   // doesn't work in Opera < 9
   myiframe.load( function() {
       var w = this.contentWindow;
       if(!w) w = myiframe[0]; // IE
       alert("Number of anchors: " + w.$("a").size());
       alert("Document title: " + w.document.title);

Several things to note:

  • In Internet Explorer, if you navigate to a different page in the iframe, the load event is not fired again.
  • The iframe needs the id and name attributes to both be present and the same.
  • The iframe page also needs to include jQuery

Thursday, February 22, 2007

Registry-less Programmer's Notepad 2

Programmer's Notepad 2 can be made to run without using the registry (i.e. make it portable, so you can use it on a removable hard drive / pen drive), but only with a development build. All it needs is a config.xml in its directory containing the following:

  <userSettings path="settings" />
  <storeType value="Xml" />

Alternatively, this batch file can be used to create the file and copy over your settings. Create a batch file e.g. pn2local.cmd and paste in the following code:

@echo off
if exist config.xml goto copysettings
echo ^<config^> > config.xml
echo    ^<userSettings path="settings" ^/^> >> config.xml
echo    ^<storeType value="Xml" ^/^> >> config.xml
echo ^<^/config^> >> config.xml
md settings
xcopy "%AppData%\Echo Software\PN2\*.*" settings\ /D /Q

Tuesday, February 20, 2007

Remove multiple options with removeOption

removeOption, a plugin available along with my other select box manipulation ones can now take a regular expression as the parameter. This can be used to remove more than one option in one go (or even all of them).

Wednesday, February 14, 2007

Select box manipulation with jQuery

If you read the jQuery mailing list, you may be aware that I have updated my plugins for working with select boxes. Summary of changes:

  • addOption replaces any options with the same value (so think of it as an add/replace options plugin
  • selectOptions selected options in addition to what was already selected, but there is now an option for it not to do this
  • There are two new methods:
    • copyOptions which is for copying options between select boxes
    • ajaxAddOption allows you to add options via AJAX (i.e. could be used for create options dynamically from a server script)

Monday, February 05, 2007

Adding a WebControl before or after another one (ASP.NET C#)

ASP.NET does not directly allow you to add a WebControl after another one (i.e. you can't do MyRepeater.AddAfter(MyLiteral) to add MyLiteral after MyRepeater. These two simple functions allow you to do just that:

public void AddControlBefore(Control beforeControl, Control controlToAdd)
 Control container = beforeControl.NamingContainer as Control;
 container.Controls.AddAt(container.Controls.IndexOf(beforeControl), controlToAdd);
public void AddControlAfter(Control afterControl, Control controlToAdd)
 Control container = afterControl.NamingContainer as Control;
 container.Controls.AddAt(container.Controls.IndexOf(afterControl) + 1, controlToAdd);

Tuesday, January 30, 2007

jQIR - jQuery Image Replacement (updated)

Get jQIR to replace contents of tags (e.g. headings) with images. Can now use class as well as id.

Friday, January 26, 2007

Firebug 1.0

If you are a web developer and use Firefox, you are likely to have heard of Firebug. The final version of Firebug 1.0 is out, and offers a lot more than the previous version (0.4.1). So I would suggest you to Get Firebug if you haven't already.

It is great for debugging as you can edit/inspect HTML and CSS on the live page and set breakpoints in JavaScript. If only Internet Explorer had something like this (I am aware of the Microsoft Script Editor (comes with Office and is activated within Word/Excel etc by pressing Alt+Shift+F11) and Visual Studio, but they are external applications and don't allow debugging while in the browser).

Firebug is even handy for non-developers (if they are interested in moving into development) as you can see the scripts and CSS pages are using, as well as see what files are being downloaded by the browser (including those downloaded by Flash).

Friday, January 19, 2007

Getting jQuery Version

There is a way of getting the jQuery version, but it is not through using jQuery.version as you may expect.

alert("jQuery version is: " + jQuery().jquery);

Here is a basic function that can be used to grab more valuable information from this.

function jQueryVersion()
 var ver = (new jQuery()).jquery;
 // if there are two .'s it is a bug fix release
 if(ver.match(/\./g).length == 2)
  return {
   "version" : ver,
   "major" : ver.substr(0, ver.indexOf(".")),
   "minor" : ver.substr(ver.indexOf(".") + 1, ver.lastIndexOf(".") - ver.indexOf(".") - 1),
   "revision" : ver.substr(ver.lastIndexOf(".") + 1)
 // otherwise it is an initial release
  return {
   "version" : ver,
   "major" : ver.substr(0, ver.indexOf(".")),
   "minor" : ver.substr(ver.indexOf(".") + 1),
   "revision" : 0

This could be handy when developing plugins, as they could alert the user if they are using a version of jQuery not supported.

jQuery.fn.myplugin = function()
  var version = jQueryVersion();
  if(parseInt(version.minor) < 1)
    alert("jQuery version 1.1 or higher is required for myplugin");
    return this;

Thursday, January 18, 2007

Link: Sites Using jQuery

Several high profile sites use jQuery. The jQuery Wiki has a page listing those sites: Sites Using jQuery

Tuesday, January 16, 2007

Checkbox manipulation with jQuery

Updated my plugins for working with checkboxes http://www.texotela.co.uk/code/jquery/checkboxes/

Toggle, check, uncheck and make them behave like radio buttons.

Works with jQuery 1.0 and 1.1.

You supply the container, and optionally return the check items (if using toggleCheckboxes or checkCheckboxes) or unchecked items (unCheckCheckBoxes):

$("#mycontainer").toggleCheckboxes("[@name=foo]", true).doSomethingWithCheckedBoxes();

For turning a checkbox group --> radio style selection:


Monday, January 15, 2007

jQuery Documentation

Update 24 Feb 2007: Link to Sean O's jQueryHelp

Update 23 Feb 2007: Added links for PDF's of API

Update 29 Jan 2007: Jörn Zaefferer's API browser is no longer a draft. Link below. 22:10 it also is printer friendly and can be downloaded for offline viewing. Visual jQuery 1.1.1 is also now available (and can also be downloaded).

Update 18 Jan 2007: A PDF Version of the documentation is available. To download, go to JQuery documentation in PDF. Only for the latest version of jQuery (1.1), although those with experience with Java will probably be able to check out an older version to generate the documentation.

If you are a user of jQuery, it is likely that you are aware of Visual jQuery, which is an alternative reference for the jQuery API. What you may not know, is that on the site is documentation for other versions as well (so if you still use an older 1.0.x version, you can still see it on the site). Here are the links (that I know of) to the documentation of the various versions. Also included is the blog post announcing the release of each version, with details of bugs fixed, feature changes etc.

There are also several other places that have their own version of the API documentation:

  • jQuery API (the original API page, hopefully it will still be kept up to date when new versions come out)
  • jQuery Documentation Wiki
  • Draft API jQuery API Browser by Jörn Zaefferer (one of the key developers of jQuery) There is also an application you can download (no install required) that allows you to look up a function in this API browser by simply highlighting it and pressing Ctrl-Shift-J - Sean O's jQueryHelp
  • gotapi.com also has it (version 1.0.3), but unfortunately the jQuery API page on the site can't be bookmarked, so it has to be clicked on in the centre frame

It also available in PDF format:

There are probably more that I have missed which I will hopefully be able to add to this post.

What I have not seen yet, is a PDF or a CHM (HTML Help) version of the documentation. Both It would be valuable for browsing offline (although I doubt many web developers now are offline very often) and searching can be easier and faster. Thankfully there is an XML version of the documentation (available on the jQuery API page and in the post announcing 1.1) that could be used to generate a PDF or CHM file. I am not sure if the XML files for the older versions (i.e. 1.0.x) are still available though.

Wednesday, January 03, 2007

Associative Arrays in JavaScript

Some developers misuse the Array constructor to create an associative array. However, this is not a good way of doing this as all the methods/properties available to an array (length, index, sort etc) will not work.

var foo = []; // [] is the same as 'new Array()'
foo["bar"] = "baz";

When the alert fires, it will return '0' instead of '1'.

As it doesn't function as a proper array, you may as well use an object instead:

var foo = {}; // {} is the same as 'new Object()'
foo["bar"] = "baz";

However, you can't see how many items there are without looping through the object. I have written a simple class that can be used that offers this (through the function 'getSize()' as well as a few other methods). As a result, you can't have anything with the keys 'getSize', 'remove', 'toString' and 'toArray'.

var AssociativeArray = function()
 if(arguments.length == 1 && arguments[0].constructor == Object)
  for(var item in arguments[0])
   this[item] = arguments[0][item];
 this.getSize = function()
  var length = 0;
  for(var item in this)
   if(item in new this.constructor === false)
  return length;
 this.remove = function(item)
  if(item in new this.constructor === false)
   delete this[item];
 this.toString = function()
  return this.toArray().toString();
 this.toArray = function()
  var output = [];
  for(var item in this)
   if(item in new this.constructor === false)
    output[output.length] = item + "=" + this[item];
  return output;

To use this is pretty simple:

var foo = new AssociativeArray();
foo["one"] = 1;
foo["two"] = new Date();
foo["three"] = "A string";
// the above can also be done like this:
// var foo = new AssociativeArray({"one":1,"two":new Date(),"three":"A string"});
alert(foo); // alerts a comma separated string containing the items added
alert(foo.getSize()); // alerts the size (i.e. 3)
foo.remove("one"); // remove item 'one'
alert(foo.getSize()); // alerts the new size (i.e. 2)
var ar = foo.toArray().sort(); // sorted array (by key)

Link: Code Snippets

Code Snippets is a public source code repository where you can add your own and share them as well as browse existing ones by tags. Unfortunately it lacks search facilities or a way of navigating by multiple tags (i.e. you can not find snippets with the tag 'array' and 'javascript').