Destructuring assignments in JavaScript 1.7

August 13th, 2009

Destructuring assignments are great for time saving methods of assigning values to variables. They make for shorter code, and shorter code is less error prone.

A destructuring assignment essentially allows you to arrange variables in an arrayesque manner, and assign them an array. What this does is actually assign the items in the array to each variable in one go. This is much easier to explain with an example.

Say we have two variables:

var variable1 = 10, variable2 = 20;

Now, we want to assign them two new values. By putting those variables inside an array-like structure before the assignment operator, we can do this in one statement instead of two:

[variable1, variable2] = [30, 40];

Now, variable1 is 30, and variable2 is 40. We can use this to take all of the items of an array returned from a function and put them in individual variables:

var color1, color2, color3;
var fnGetColors = function() {
	var arrColors = ['red', 'green', 'blue'];
	return arrColours;
};
[color1, color2, color3] = fnGetColors();

Or to swap the values of two variables, which previously would have required a temporary variable to use for storage:

var strBlack = '#FFFFFF';
var strWhite = '#000000';
//Oops, wait - that's not right
[strBlack, strWhite] = [strWhite, strBlack];

Sadly, support for JavaScript 1.7 is patchy. Internet Explorer, even in version 8, still only supports JavaScript 1.5. This kind of code could be useful if you were writing extensions for Firefox though, or had control over your user base (perhaps in an Intranet). I include it here just for interest – one day we’ll be able to use it!

Further reading:
New in JavaScript 1.7 – MDC
JavaScript Versions on Wikipedia

Share this Article:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Add to favorites
  • email
  • FriendFeed
  • LinkedIn
  • Netvibes
  • Reddit
  • Slashdot
  • StumbleUpon
  • Tumblr
  • Twitter

booshtukka JavaScript

My track featured on PlanetBadminton Video

June 15th, 2009

My track “Cosmopolitan” features on a PlanetBadminton video – thanks to Simon Pollock.

Share this Article:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Add to favorites
  • email
  • FriendFeed
  • LinkedIn
  • Netvibes
  • Reddit
  • Slashdot
  • StumbleUpon
  • Tumblr
  • Twitter

booshtukka Booshtukka, Music

My opinion of Skype on Three

May 14th, 2009

3 asked me to make a video with my thoughts on using Skype with their handsets. I am a big supporter of anything that gives me free phone calls! You can see the video on the 3 Bebo page.

Share this Article:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Add to favorites
  • email
  • FriendFeed
  • LinkedIn
  • Netvibes
  • Reddit
  • Slashdot
  • StumbleUpon
  • Tumblr
  • Twitter

booshtukka Skype

Regular Expression to match UK residential telephone numbers

May 13th, 2009

A regular expression to match UK residential telephone numbers. It understands the difference between 02 and 01 numbers. It will accept all common formats and internationally formatted numbers.

Examples of accepted numbers:

  • 02081234567
  • 0208 123 4567
  • 020 8123 4567
  • 0208 123-4567
  • +44 208 123 4567
  • +44 (0) 208 123 4567
  • 01234 567 890
  • +44 0 1234 567-890
  • 07712 123 456

Examples of numbers that will not be accepted:

  • 020812345678
  • 123456789
  • 07612 123 4567
  • +33 345 876 1298

This is my first submission to the excellent regexlib.com regular expression library – I’d appreciate if you could vote for it!

/^((\(44\))( )?|(\(\+44\))( )?|(\+44)( )?|(44)( )?)?((0)|(\(0\)))?( )?(((1[0-9]{3})|(7[1-9]{1}[0-9]{2})|(20)( )?[7-8]{1})( )?([0-9]{3}[ -]?[0-9]{3})|(2[0-9]{2}( )?[0-9]{3}[ -]?[0-9]{4}))$/

Let me know if I’ve missed anything!

Update: This has been amended as per comments below, to allow 020 as a prefix for London, 07624 (Isle of Man) and 074xx xxxxxx.

Share this Article:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Add to favorites
  • email
  • FriendFeed
  • LinkedIn
  • Netvibes
  • Reddit
  • Slashdot
  • StumbleUpon
  • Tumblr
  • Twitter

booshtukka JavaScript, RegEx

Amber Mac mentions me in an article on Nicecast

May 12th, 2009

Amber Mac recently asked on Twitter if anyone had experience with Nicecast. I chimed in, and she asked if she could quote me in an article she was writing. I was only too happy to oblige, and here is the result.

Share this Article:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Add to favorites
  • email
  • FriendFeed
  • LinkedIn
  • Netvibes
  • Reddit
  • Slashdot
  • StumbleUpon
  • Tumblr
  • Twitter

booshtukka Booshtukka, DJing, Music

Centre div in window no matter what – Version 2

April 22nd, 2009

In a previous post I showed you how to center a div on screen regardless of if it was inside an iframe or not. This is the second version, which should work regardless of if the div is in the top level window, an iframe, or a regular frame.

/******************************************************************
	Name: center
	Description: Center a div on page, no matter what!
	Author: AK (www.zeroedandnoughted.com)
	Date: 22nd April 2009
	Version: 0.2
	Dependencies: jQuery
	Notes:
	******************************************************************/
	(function($) {
	    $.fn.center = function() {
	        return this.each(function() {
				var $this = $(this);
				var frameXOffset = 0, frameYOffset = 0, windowHeight = 0, windowWidth = 0;
				//Are we in a frame?
				if (top.document != window.document) {
					var frm = $('iframe',top.document.body);
					if (frm.length == 0) {
						//regular frame
						frm =  $('frame',top.document.body);
					}
					var i=frm.length;
					while (i--) {
						if (frm[i].contentDocument) {
							doc = frm[i].contentDocument;
						} else {
							doc = frm[i].contentWindow.document;
						}
						if (doc === document) {
							//located our frame!
							frameXOffset = $(frm[i]).offset().left;
							frameYOffset = $(frm[i]).offset().top;
							break;
						}
					};
					if (jQuery.browser.msie) {
						windowWidth = top.window.document.documentElement.clientWidth;
						windowHeight = top.window.document.documentElement.clientHeight;
					} else {
						windowWidth = top.window.innerWidth;
						windowHeight = top.window.innerHeight;
					}
				} else {
					//we are not in a frame
					if (jQuery.browser.msie) {
						windowWidth = window.document.documentElement.clientWidth;
						windowHeight = window.document.documentElement.clientHeight;
					} else {
						windowWidth = window.innerWidth;
						windowHeight = window.innerHeight;
					}
				}
				var elHeight = $this.height();
				var newTop = ((windowHeight/2) - (elHeight/2)) - frameYOffset + $(parent.document.documentElement).scrollTop();
				if ((newTop + elHeight) > $(document).height()) {
					newTop = $(document).height() - elHeight;
				}
				$this.css ({
					left: ((windowWidth/2) - ($this.width()/2)) - frameXOffset + $(parent.document.documentElement).scrollLeft(),
					top: newTop
				});
			});
		};
	})(jQuery);
Share this Article:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Add to favorites
  • email
  • FriendFeed
  • LinkedIn
  • Netvibes
  • Reddit
  • Slashdot
  • StumbleUpon
  • Tumblr
  • Twitter

booshtukka JavaScript, jQuery

Checking for Duplicates in a JavaScript Array

April 7th, 2009

JavaScript has an in operator, that allows us to look through an object to see if we can find a property. If we create an object containing particular items in an array, we can then look through those items to see if we find a match.

Using prototypes, we can easily create a new method that will apply to all arrays. Let’s look at this in pieces.

The first thing we want to do is attach a method to the array prototype.

Array.prototype.containsDuplicates = function() {};

We can now do something like:

var dupesFound = [1,2,3].containsDuplicates();

…although this will won’t yet return anything, of course.

The next thing we’ll want to do, is loop through the contents of our array. For each item we will need to create an array with every item except our current one to check against (otherwise we will match against our current item, and always find a match).

In my previous post on iterating through arrays we already know the fastest way to iterate through an array (assuming we don’t mind doing it in reverse) so we’ll do that, and for each iteration create a new array containing all but the current item using the slice() and concat() methods.

var i=this.length;
var a;
while (i--) {
	a = this.slice(0,i).concat(this.slice(i+1,this.length));
}

Next, we’ll create an object and loop through our new array, creating an empty property of the object for each item in the array.

o = {};
j = a.length;
while (j--) {
	o[a[j]] = '';
}

Finally, we can now check this object for our current item, and return true if we found a match.

if (this[i] in o) {
	return true;
}

So, putting it all together (remembering to return false if we don’t find a match:

Array.prototype.containsDuplicates = function() {
	var i=this.length;
	var a, o, j;
	while (i--) {
		a = this.slice(0,i).concat(this.slice(i+1,this.length));
                o = {};
                j = a.length;
                while (j--) {
                    o[a[j]] = '';
                }
		if (this[i] in o) {
			return true;
		}
	}
	return false;
};

I generally don’t advocate modifying the base prototypes in JavaScript – it can cause all sorts of problems later on, so here’s the same methodology as a function.

var containsDuplicates = function(a) {
	var i=a.length;
	var a2, o, j;
	while (i--) {
		a2 = a.slice(0,i).concat(a.slice(i+1,a.length));
                o = {};
                j = a2.length;
                while (j--) {
                    o[a2[j]] = '';
                }
		if (a[i] in o) {
			return true;
		}
	}
	return false;
};

I hope this helps someone. Feel free to suggest ways to make this more efficient.

Share this Article:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Add to favorites
  • email
  • FriendFeed
  • LinkedIn
  • Netvibes
  • Reddit
  • Slashdot
  • StumbleUpon
  • Tumblr
  • Twitter

booshtukka JavaScript

Building Accessible Websites – Part 1: Visual Impairment

February 23rd, 2009

The statistics from the RNIB show that 5.9 children in 10,000 have some kind of visual impairment. There are around 80,000 people in the UK that are registered as blind or partially sighted. That is a significant number of people, and if your website can expect a reasonable amount of traffic it is a number you should be paying attention to. Quite apart from that, it is a legal requirement that we do not discriminate against people in any way. If your data is public, everyone should have access to it.

The Disability Discrimination Act makes it unlawful for a service provider to discriminate against a disabled person by refusing to provide any service which it provides to members of the public. From webcredible.

Fortunately, building websites in a semantic and SEO-friendly manner has the side effect of making a site that is likely to be screen-reader friendly. That is – if you are building websites well, the issues this kind of impairment presents are less problematic than you might expect.

Screen readers

Users who are considerably visually impaired will employ some kind of screen reader to help them use their computer. For the web, this is a tool the gives the user methods to hear the text on a site, and quickly jump to sections of a page. A lot of screen readers are available, and they all work in slightly different ways (like web browsers or mobile web browsers). They are very expensive to upgrade, and upgrades are available often, and because of this it is my experience that many users do not often upgrade screen readers. Many screen readers do not allow JavaScript, and those that do typically make it easy to disable. I usually make the assumption that a screen reader user will have JavaScript disabled, although where easy I do anything I can to make JavaScript as screen reader friendly as possible. A lot of JavaScript enhancements for a user with normal eyesight will not be of much use to a screen reader user anyway. Having watched experienced users of screen readers, I can say that they are able to make use of an accessible website very quickly indeed, and listen to the text being read out at upwards of 180 words per minute! At that speed, to me it just sounds like gibberish. Apple’s VoiceOver can apparently speak intelligibly at over 750 words per minute.

Using a Firefox extension such as Fangs will let you emulate a screen reader’s behaviour, to a degree. Use this to help you get the hang of building a page in a linear fashion – remembering you need to describe things before they happen, not after.

Semantic HTML

The first rule is to apply POSH to all of your content. This is an important rule anyway, for the semantic web. The importance of this is beyond the scope of this article, and I will revisit it in a dedicated blog entry in the future. Most screen readers are able to quickly offer the user an audible representation of an outline of the document, for example, all of the level two headings on a page, or all of the forms on a page. Using POSH has many other benefits including SEO, consistent and higher quality code, validating code and future-proofing.

Skip links

Using in-page anchors to allow the user to jump to sections of the page is vital. At the very least they allow the user to jump straight to the navigation and the main content. If these anchors do not fit your design, use CSS to give these position: absolute; and left:-9999px;. Although we cannot guarantee this in the future, current screen readers typically will not read out content that is display: none; or visibility: hidden; (assuming, correctly that it is not visible) but they will read out content that is positioned off-screen. To make these more useful you can use a CSS :focus selector to bring these links back into view when the user uses the keyboard to tab to them, benefiting all other users at the same time. Use the same trick for “Back to Top” links and your user now has a way to leap around your page, without having to listen to all the content.

Consider links as holistic entities

Users of some screen readers have the ability to immediately list (audibly) all of the links on a page. These are (usually) listed one at a time, as the text (or alt text) inside the anchor tags. This means if your text says something like “click here to go to website A”, a screen read user will hear just the word “here”. If you have this all over the page they will hear just “here”, “here”, “here” and so on, which is not useful – in fact, very frustrating. Instead, try to make the links an entity in their own right, something more like “go to website A“. Where this is difficult, for example at the end of an excerpt from an article you might have a link that says “more…” that takes you to a page that details the entire article. You could actually surround this in other text so the text says “more about this article on wombats…” and ” about this article on wombats” is in a span which employs the same trick as above to take it out of the flow and position it off-screen.

AJAX/DOM hooks

When you use JavaScript to modify the contents of the page (perhaps as a result of an AJAX call), the screen reader may be reading at a position below that point. The screen reader may not notice that the contents of the page have been changed, meaning the user will have to start reading the page again at the top to find the change. There are methods you can employ to try to give a screen reader hints that the page has changed, and to offer the user a chance to leap to that point. The full extent of this is beyong the scope of this article, but ajaxian provide a great guide to accessible AJAX best practices.

Frames/iFrames == Bad

Quite aside from the plethora of other reasons you should be avoiding frames, they make the life of a screen reader very difficult. Which frame should we currently be reading? When do we jump focus to another? How do we present audibly that these are different entities, if in fact they are? Frames were designed to help solve a problem, but they ultimately just create more problems says www.webaccessstrategies.com and I concur.

Magnifiers

Most operating systems give the user the ability to zoom in on any part of their screen. This works operating system wide, not just for web browsers. Applications can be acquired to achieve the same end, and this is really how accessibility should be handled – in a consistent, system-wide fashion. Since all these are doing is helping the user focus on a section of the page, the only caveat here is to remember to try to stop our paragraphs or blocks of text from being too wide (within reason) so the user does not have to endlessly jump back and forth to read sentences. Keeping our text in reasonable width blocks like this will also help some people with learning disabilities (to be covered in a future post) to read our content.

CAPTCHA

CAPTCHAs help us try to ensure our website is being accessed by a real person. It is vital to accept these are not fool-proof. A computer program can be formulated to read any text that we can, especially if the operational parameters of a particular CAPTCHA can be figured out. Even if you are really clever (recently I saw a CAPTCHA showing nine women, one of which was clearly more attractive than the others) techniques can be used to get around this. One pornographic site presented users with a CAPTCHA from Yahoo! when they were signing up, so that without knowing, they were actually helping the site build fake Yahoo! accounts in the background. (CNET story.)

Whilst they cannot be relied upon, CAPTCHAs just make it that bit more difficult for someone trying to abuse your site. As we know, in essence, they present you with an image and ask you questions about it. It is possible to also present this data audibly, but by now this is a huge undertaking to do well, and one more thing you don’t really need to be developing and supporting. To address these issues, I cannot recommend the reCAPTCHA project enough. Not only are you using an API to implement a mature and working CAPTCHA with audio and skinning support, your users are also helping to digitise books! Read more at the reCAPTCHA site for details.

Scalable text

The text on your site should all be in a relative unit be in based on percentages or “ems”. According to Wikipedia An em is a unit of measurement in the field of typography, equal to the point size of the current font.. You should be able, as a rule of thumb (my thumb, in this case) to resize your font up or down by two sizes. Resizing up has an obvious value – it makes the text easier to read. I have even done this. Running a Mac Mini on a big screen TV at HD resolution actually makes text impossible to read. Until we get resolution independence, jumping the font size up a couple of sizes provides a quick fix. You also need to be able to turn the font-size down, which may surprise some people but it’s important that text remains readable even when using the “Smallest” setting. This is important for users with tunnel vision who may wish to fit as much text in their line of sight as possible (from the RNIB Web Access Center).

The most recent browsers are now starting to scale up the entire page when the user chooses to increase font-size (though they can sometimes choose to isolate this effect to text only) resulting in pixelly graphics, but maintaining layout. For maximum compatibility, liquid layouts will cope better with text-only font size changes, and can help maximise the use of a browser’s screen estate at different resolutions. I recommend not going over the top with this. Supporting resolutions of 800 x 600 up to 1440 x 900 is a reasonable thing to do, but although supporting an HD resolution might be technically impressive, an entire paragraph on a single line is not easy to read, nor does it normally look attractive.

Colour blindness

The BBC has a tool (internally referred to as “Barlesque”) which allows the user to set various display options according to their impairment. Several colour schemes are available, which are appropriate for different levels and types of colour blindness. These sittings change a stylesheet which is applied to the site, for different colour schemes which users will find easier to read. For those of us who cannot afford the luxury of implementing this kind of functionality, our goal must be to expect a reasonable lever of contrast between text and the background. Snooks have a tool to tell you the brightness and colour difference between two colours, and whether or not the contrast ratio is acceptable. I would suggest their acceptable levels are a bit unrealistic, and you should be trying to aim for 125 or more brightness difference, and 400 or more colour difference. Access Keys also provide a tool to scan an entire page and give you a report on the contrast of text on that page.

Images and alt text

Images should only have alt text where the image has value as content. Alt text is “alternate” text. This means it is an alternative to the image, for users who have chosen not to download images or are not able to view them. If a link is an image that has the text “Order Now” on it, it needs an alt attribute that says “Order Now”. If it is a swirly blue pattern, or someone looking happy using a computer, or any other kind of image that does not provide value to the page other than aesthetically, it does not need alt text. It does need to have an alt attribute, to validate, but that attribute can be empty.

Where you have extra information to include such as copyright data for an image, or detailed descriptions of the location the title attribute is more appropriate. Where this information is very lengthy, the longdesc attribute can contain the address of a page with more details.

Pet hate: it is not an alt tag! It is alt text, or (more accurately) an alt attribute.

Consistency

Try your absolute hardest to keep the layout and style of your pages consistent. If the user can always expect to find the content here and the navigation here, they can learn to navigate your site more efficiently very quickly. If you are employing skip links too, they will rapidly learn where these are and where they lead.

Some extra resources

In the next part of this series, we will look at hearing impairments.

Share this Article:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Add to favorites
  • email
  • FriendFeed
  • LinkedIn
  • Netvibes
  • Reddit
  • Slashdot
  • StumbleUpon
  • Tumblr
  • Twitter

booshtukka Accessibility, HTML

Poor Hitler's build is broken

February 19th, 2009

…and Steiner doesn’t have enough RAM for his VM. Adolf only wants nightly builds. Remember what happened to Stalin!

Share this Article:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Add to favorites
  • email
  • FriendFeed
  • LinkedIn
  • Netvibes
  • Reddit
  • Slashdot
  • StumbleUpon
  • Tumblr
  • Twitter

booshtukka Agile

Making web service APIs that play nicely

February 15th, 2009

We are part of the way through writing stories for the next Silver Squid project and I thought I would share some of these to do with the basic requests and responses of our web service APIs.

Choosing Data Types

Something that I feel is important, is to allow the user of your APIs to send and receive data in the format of their choice. They may be trying to integrate your system with one that only speaks one language, or they might be better versed in some than others.

With that in mind, our latest project allows the user to set whether they are sending data as a normal form submission (necessary in this instance, to allow the user to send files), as XML or as JSON. We allow these to be set in HTTP headers, so that they are set before the system examines the sent data at all. The story is as follows:

As an API user
I want to be able to send HTTP headers defining my request and response data types
so that I can better integrate the API with my system

Acceptance criteria:

  • M: A requestDataType header can be sent – the values can be: form, xml or json. This should dictate the expected data and default to form: if not provided.
  • S: If requestDataType is set to a different value the error ERR_UNSUPPORTED_REQUESTDATATYPE should be thrown.
  • M: A responseDataType header can be sent – the values can be: xml or json. This should dictate the response data type, and default to xml if not provided.
  • S: If responseDataType is set to a different value the error ERR_UNSUPPORTED_RESPONSEDATATYPE should be thrown (in XML).

I have begun to employ the MoSCoW Method for acceptance criteria priorities. According to Wikipedia – these are defined as:

M
MUST have this.
S
SHOULD have this if at all possible.
C
COULD have this if it does not affect anything else.
W
WON’T have this time but WOULD like in the future.

It is very helpful to have a convention to follow for things like this, and this method seems as good as any other.

Consistent Errors

You’ll see that I have defined the errors that will be thrown, and specifically stated that when the Response Data Type cannot be inferred, to use XML.

I try to always be very specific about the error that will be thrown, and to throw those errors in a consistent manner. It feels natural to me to throw HTTP errors when our API fails, and for a while I tried to always throw the appropriate HTTP error code. I gave up on this, because there just is not always an appropriate error code. Now we always throw a 500 error, and provide a string describing the specific error, in the format requested by the user. The story in this project that defines this is:

As an API user
I want errors to be thrown in a consistent fashion
so that my system can detect these and respond appropriately

Acceptance Criteria:

  • M: When an error is thrown, the system should return an HTTP error code of 500.
  • M: When an error is thrown and responseDataType is set to xml (or missed out and thus defaulted), the error should take the following format:
    <?xml version="1.0" encoding="UTF-8"?>
    <rootNode>
    	<error>ERR_CODE</error>
    </rootNode>
  • M: When an error is thrown and responseDataType is set to json, the error should take the following format:
    {"error":"ERR_CODE"}
  • S: All error codes should begin with ERR_.
  • S: A default error of ERR_UNSPECIFIED_ERROR should be thrown when we can not further isolate the error.

This should make it easy to predict the error formats, and also make them easier to write. Knowing that all errors will begin with “ERR_” allows the user of our API to easily handle for all errors, and add more specific handlers when/if necessary, although checking for an error property or node is enough to detect that an error was thrown.

I hope this has been useful. How do you deal with errors and data types in your APIs?

Share this Article:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Add to favorites
  • email
  • FriendFeed
  • LinkedIn
  • Netvibes
  • Reddit
  • Slashdot
  • StumbleUpon
  • Tumblr
  • Twitter

booshtukka Agile