Speech Input Fields with HTML5

Before the fun begins – beware you’ll need to test this page with Chrome.

This is one of those ‘pixie fairy magic’ features that get gifted to web developers from time to time. Speech input fields let you speak to the browser (yes the browser) and it will recognise what you say and enter it in a form field. Don’t believe me try the example:

Speech Input Field Example

Impressed? Well I was and here is the code. First up you need to create a HTML input field. This can be of various types including the new HTML5 variants ie ‘text’, ‘search’, ‘number’ – anything that requires text type input. Add to this the attribute ‘speech’ as follows:

<input type="text" id="speakToMe" speech>

Now if you took a look at the code in the demo then you’ll notice that I am not quite telling the truth here. The ‘speech’ attribute is not standardised so we have to use a vendor prefix, an experimental prefix at that. So the HTML used is:

<input type="text" id="speakToMe" x-webkit-speech>

This feature is documented as a draft API by W3C. Various methods and events are suggested in this document.

The W3C draft specification indicates that <textarea> elements should work with the ‘speech’ attribute but from my experiments this doesn’t seem to have been added to Chrome just yet (April 2012).

Speech Input Methods

The following methods are available to the speech input API.

startSpeechInput()
Starts a a new speech input session.
stopSpeechInput()
Stops the speech input session.
cancelSpeechInput()
Cancels the speech input session

Speech Input Events

The following events can be associated with speech input fields.

capturestart
Dispatched when audio capture session starts
speech start
Dispatched when the active speech input session detects that the user has started speaking.
speechchange
The speechchange event is dispatched when a set of complete and valid utterances have been recognized. This event bubbles. A complete utterance ends when the implementation detects end-of-speech or if the stopSpeechInput() method was invoked.
speechend
Dispatched when the active speech input session detects that the user has stopped speaking.

To experiment with these in Chrome use the webkit vendor prefix ie:

<input type="text" id="speakToMe" onwebkitspeechchange="checkName();" x-webkit-speech />

Speak up I didn’t hear you.

Getting Starting with Google Maps

There is a Swansea but to get there you’ll probably need a map … a Google Map. So here are some quick examples to get you started.

All of the following use Google Maps Version 3.

Adding a Google Map means adding some Javascript to your page and accessing the Google Maps API.

Note: When the Google Maps API first appeared in 2005 it was free to use. In November 2011 Google introduced licensing for high volume users and this has lead some sites to jump ship to other mapping services in particular Openstreetmap.

Getting Started

We are aiming to produce this:

First thing you’ll want to do is sign up with Google and get yourself an API key. Sign up to Google here.

Calling the API

Once you have a key, this is then used in your call to the Google Maps API as follows adding your key where I have put ‘YOUR-KEY-HERE’ :

<script type="text/javascript"
      src="http://maps.googleapis.com/maps/api/js?key=YOUR-KEY-HERE0&sensor=true">
</script>

The ‘sensor’ parameter above can be set to ‘true’ or ‘false’. This indicates whether you wish to use the likes of GPS to determine the user’s location – a feature of most mobile web browsers.

Warning: You must add a value for ‘sensor’. It cannot be left blank. Your request to the API will fail if it is missed out.

Depending on your preference to managing your Javascript, the call to the API could go either in the <head> of your HTML or before the closing </body> in your HTML.

Creating a Placeholder

We now need to add some HTML to the web page that will act as the placeholder for the map. In most cases a <div> tag with an ID is the best approach. (You don’t necessarily have to do this but you do need a targetable bit of HTML and this is as good a way as any).

<div id="myFirstMap">

</div>

Ensure that you styling gives the placeholder the dimensions you wish for your map.

<style type="text/css">
#myFirstMap{
			width:640px;
			height:480px;
			border:1px solid #FC0;
}
</style>

Setting Map Options

The Google Map API has a huge range of options that can be applied to your map. However, some of these aren’t really ‘optional’ as for example you’ll need to at least provide a latitude and longitude value to get a map!

These ‘options’ are declared in a Javascript object. Here is a basic example that includes a LatLng value, a zoom value and a map type.

var myOptions = {
          center: new google.maps.LatLng(53.3801, -1.4653),
          zoom: 16,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };

Creating the Map Object

To create the Map object itself we need to reference our placeholder and the options created above. I am using Javascript’s getDocumentById here to reference the <div> of ID ‘myFirstMap’

var map = new google.maps.Map(document.getElementById("myFirstMap"), myOptions);

The above is placed in a function with the options object as follows:

<script>
function initialize(){
	var myOptions = {
          center: new google.maps.LatLng(53.3801, -1.4653),
          zoom: 16,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
     var map = new google.maps.Map(document.getElementById("myFirstMap"), myOptions);
      }
</script>

Firing the Code

The above function needs to be called when the document is ready. You could use jQuery here but I’ll keep it in plain old Javascript for now.

We’ll kick off the Javascript with an onload event against the <body> tag.

<body onload="initialize()">

You’ll need to take a trip to the Google Maps documentation at some point but hopefully you can now find your way to Swansea.


Here are a few more pointers.

More on Options

The Google documentation is exhaustive (and exhausting). It helps if you have some grasp of basic programming jargon like classes, object, properties, methods and events . To help you on your way here are of some of the most popular map options set in the MapOptions object.

center
LatLng object from LatLng Class
zoom
0 full globe – higher numbers to zoom in ie 7, 18
mapTypeId
ROADMAP, SATELLITE, HYBRID, TERRAIN
mapTypeControl
Boolean disable/enable map type controls
panControl
Boolean disable/enable pan controls
streetViewControl
Boolean disable/enable street view controls
zoomControl
Boolean disable/enable zoom controls

In a code context these would look as follows:

function initialize(){
	var myOptions = {
          center: new google.maps.LatLng(51.62437128841585, -3.9431847585819924),
          zoom: 10,
          mapTypeId: google.maps.MapTypeId.HYBRID
          mapTypeControl: false,
          panControl: false,
          streetViewControl: false,
          zoomControl: false,
};
var map = new google.maps.Map(document.getElementById("myMap"), myOptions);
}

Markers

Markers or ‘pins’ are a crucial part of any map. They are created by declaring a marker object from the Marker class. When creating a marker object it can take a number of parameters passed to it as a MarkerOptions object. In the following example the marker is given a lat/lng, assigned to a map object, given a title and made draggable.

var marker = new google.maps.Marker(
  {position: myLatlng,
  map: myMap,
  title:"Hello World!",
  draggable: true}
  );

The Google documentation gives you the full range of possibilities.

InfoWindows

InfoWindows are the speech bubble effects that can be attached to markers. These are achieved through the InfoWindow class.

var infowindow = new google.maps.InfoWindow(
{content: "Hello World"}
);
infowindow.open(map,marker);

InfoWindows are often set to respond to user clicks. The Google API lists events associated with each type of object, so for example there are a list of events associated with markers. The following example uses the ‘click’ event to open an infoWindow when a marker is clicked.

google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});

Get Position of Dropped Marker

You may have noticed above that we set the MarkerOptions ‘draggable’ to ‘true’. We can use events to capture where the marker is dropped and find the latitude and longitude of that point.

google.maps.event.addListener(marker, 'dragend', function() {
document.getElementById('currentLatLng').innerHTML = marker.getPosition()
});

The above will send the lat/long value to a HTML element of ID ‘currentLatLng’ as you can see in the demo.

StreetView with the StreetViewPanorama Class

When Google introduced StreetView in 2007 it was of those ‘wow – how did they do that – surely magic pixies’ moments. The magic is all down to the StreetViewPanorama class.

This class takes as its constructor a StreetViewPanoramaOptions object.

The following are the key properties of the StreetViewPanoramaOptions class.

position
LatLng object
pov
StreetViewPov Object – heading, pitch, zoom
addressControl
Boolean disable/enable address control
scrollwheel
Boolean disable/enable scroll wheel zoom
zoomControl
Boolean disable/enable zoom controls

The StreetViewPanoramaOptions object can be created as follows:

var panoramaOptions = {
	position: sv,
	pov: {
	  heading: 0,
	  pitch: 0,
	  zoom: 1
	},
	addressControl: false
};

Once you set your options, these are used to create the streetview and attach it to a targeted element in the HTML. In this example I am using Javascript’s getElementById to reference a HTML element of ID ‘mySV’.

var panorama = new google.maps.StreetViewPanorama(document.getElementById("mySV"),panoramaOptions);

Geolocation

With HTML5 browsers comes the possibility of getting geolocation information via JavaScript. This information can then be feed back to a Google Map.

The following Javascript allows supporting browsers to retrieve geolocation data.

navigator.geolocation.getCurrentPosition(show_map);
function show_map(position)
{
console.info(position);
}

The following codes takes the ‘position’ data from the Geolocation API and passes it to a Google map.

navigator.geolocation.getCurrentPosition(show_map);

 function show_map(position)
 {
 var latitude = position.coords.latitude;
 var longitude = position.coords.longitude;
//uses jQuery to update an HTML element of ID 'whereAmI' with the latitude and longitude
 $('#whereAmI').append('<p>Your Latitude is: '+position.coords.latitude+
 ' Your Longitude is: '+position.coords.longitude+'</p>');
 var myLatLng = new google.maps.LatLng(latitude, longitude);
 var myOptions = {
          center: myLatLng,
          zoom: 16,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
 var map = new google.maps.Map(document.getElementById("myGeoMap"), myOptions);
 var marker = new google.maps.Marker({position: myLatLng, map: map, title:"You are Here", draggable: true});
}

You can find more above the Geolocation API at the following sites.

There you go – all mapped out for you now.

Postscript: This great post is useful if you intend to load the Google Maps API dynamically with jQuery’s getScript()- http://lostmonocle.com/post/88217865/jquery-getscript-and-the-google-maps-api – thanks to Olly Hodgson.

replaceAll() function for Javascript (and ActionScript)

Ever needed to replace all the instances of a string in Javascript (or ActionScript)? This function takes three parameters, the string to find, the string to replace it, the string to search and an optional setting to toggle case sensitivity.

Syntax
.replaceAll(target:string, findToRemove:string, replacement:string, [caseSensitive:int=0 ])

function replaceAll(o,t,r,c){if(c==1){cs="g"}else{cs="gi"}var mp=new RegExp(t,cs);ns=o.replace(mp,r);return ns}

Example function call searching the string “Bob, bob and Andy”, looking to replace all occurrences of ‘Bob’ with ‘Fred’ regardless of case.

replaceAll("Bob, bob and Andy", "Bob", "Fred");

Returns ‘Fred, Fred and Andy’.

Use a value of 1 to make the search case sensitive.

replaceAll("Bob, bob and Andy", "Bob", "Fred", 1);

As this is now case sensitive it returns ‘Fred, bob and Andy’.

See this in action.

Want to know more

This is achieved using Javascript’s replace() function and regular expressions. The expanded code is:

function replaceAll(oldStr, removeStr, replaceStr, caseSenitivity){
	if(caseSenitivity == 1){
		cs = "g";
		}else{
		cs = "gi";
	}
	var myPattern=new RegExp(removeStr,cs);
	newStr =oldStr.replace(myPattern,replaceStr);
	return newStr;
}

A Regular Expression is created and given a flag of ‘g’ or ‘gi’. The g (global) flag does a global search and then ‘i’ a case insensitive search. The caseSenitivity parameter is optional and if not set then a case insensitive replacement takes place.

ActionScript Version

Javascript and Actionscript are ECMAScripts so we can port the above as ActionScript:

function replaceAll(oldStr, removeStr, replaceStr, caseSenitivity:Number=0){
	var cs:String;
    if(caseSenitivity == 1){
        cs = "g";
        }else{
        cs = "gi";
    }
    var myPattern=new RegExp(removeStr,cs);
    newStr =oldStr.replace(myPattern,replaceStr);
    return newStr;
}
///////////// example one /////////////////////
var newStr:String;
newStr = replaceAll("Bob, bob and Andy", "Bob", "Fred");
trace(newStr);
//returns "Fred, Fred and Andy"
///////////// example two /////////////////////
var newStr2:String;
newStr2 = replaceAll("Bob, bob and Andy", "Bob", "Fred", 1);
trace(newStr2);
//returns "Fred, bob and Andy"

The only difference here is the setting of the default case sensitivity value to 0, which is done directly in the parameters.

Use Case

I put this together so that I could get rid of pesky white spaces in a string and replace them with + to create friendlier URLs.

Javascript Number Format Function for Adding Commas

This seemed to take a disproportionate amount of digging to find. So for future reference here is a neat Javascript number formatting function that adds commas to large numbers. Was found at http://www.mredkj.com/javascript/nfbasic.html

		function addCommas(nStr)
		{
			nStr += '';
			x = nStr.split('.');
			x1 = x[0];
			x2 = x.length > 1 ? '.' + x[1] : '';
			var rgx = /(\d+)(\d{3})/;
			while (rgx.test(x1)) {
				x1 = x1.replace(rgx, '$1' + ',' + '$2');
			}
			return x1 + x2;
		}

Mozilla Throw in Towel on H.264?

In January 2011 Google caused a storm in a tea cup when they stated their intention to remove H.264 video support from their implementation of the HTML5 <video> tag.

But that doesn’t seemed to have happened.

At the same time Mozilla stated their support for open standards – OGG and WebM – as opposed to the royalty encumbered H.264.

So we had Google and Firefox on the one side, and on the other H.264 licence holders Apple and Microsoft.

But now Google’s open source ally seems to be weakening its stance. The onslaught of H.264 is leaving Firefox out in the cold whereas Google still haven’t dropped H.264 from Chrome.

So just as Firefox is feeling left out in the Webkit-vendor-prefix saga – it is poor Firefox that takes the flank. Firefox is obviously getting tired of playing the odd man out, trying to stick to open source principles, but with a business eye on the realities of what developers are actually using. That Google don’t put their money were they mouth is and pull H.264 support from -webkit based Chrome must be especially galling at Mozilla Towers.

Can’t say I blame Firefox for looking at H.264. Come 2016 when the H.264 license is revisited by MPEG-LA, this does potentially leave us at the mercy of Apple and Microsoft. But, hey that’s nothing new in this game.

ps I thought it timely to repost my test videos so we can see the current state of play.

Video Test Zone

To keep a track of video support, here are examples of the major players.

H.264 – in this case a 12mb mp4

If you can’t see anything above your browser doesn’t support HTML5 video with H.264

H.264 – in this case a 4mb mp4

If you can’t see anything above your browser doesn’t support HTML5 video with H.264

H.264 – in this case a 1.6mb mp4

If you can’t see anything above your browser doesn’t support HTML5 video with H.264

H.264 – in this case another 8mb mp4

If you can’t see anything above your browser doesn’t support HTML5 video with H.264

Ogg

If you can’t see anything above your browser doesn’t support HTML5 video with OGG

WebM

If you can’t see anything above your browser doesn’t support HTML5 video with WEBM

More on HTML5 Video.

Flash Player Retrenches

Adobe P P P Piss Off a Penguin

With Flash it was supposed to be build once play anywhere. But having lost the Flash Player on mobile it looks like Linux users are next in line – at least in terms of a comprehensive service.

I was at the London Flash Platform User Group’s event this week where Flash superheros Lee Brimelow and Mike Chambers were present to discuss the future of Flash. It was Mike’s unenviable task to introduce Adobe’s White Paper Roadmap for the Flash Player that was announced the previous day (22 February 2012).

Now I have been to my fair share of Adobe events over the years, doing right back to the Macromedia days, but this was something different. Gone were the whoops and continual references to awesomeness, in was a humble recognition, at least in the context of the mobile announcement, that in the words of Mike Chambers, ‘Adobe f**ked up’.

So what of the Flash Player Roadmap? Adobe have been working with Google on a project called “PPAPI” or “Pepper” a new API for hosting plugins. The bottom line is that this will be included in Chrome later this year and for Linux users will become the only way to get the Flash PLayer as a Linux Flash Player will no longer be available as a direct download from Adobe.

There are caveats here, ie a debug player will still be available and the Linux version of Flash 11.2 will be supported for another 5 years, and I know there aren’t masses of Linux users out there, but this seems to follow a general backing away from the ‘play anywhere’ philosophy that once made Flash so … erm awesome.

Gaming and Premium Video

The Flash Player Roadmap recognises that after years of browser doldrums, in recent years the browser market has been revolutionised by the efforts of Firefox, Webkit and johnny come lately IE9. The opportunities the browser doldrums offered the Flash Player are no longer relevant as the holy trinity of HTML5, CSS3 and Javascript do some serious territorial pissing.

So Adobe are retrenching the Flash Player. It is now focused on Gaming and Premium Video.

Lee Brimelow spoke about some new features coming to the Flash Player, such as disabling the right-click context menu and thus allowing it to capture events and improves to Hardware-accelerated graphics, that are clearly useful to gamers.

There was little talk about what Adobe means by ‘Premium Video’ at the event although the white paper does talk about benefits Flash has for DRM and analytics.

Gaming with Flash is still certainly streaks ahead of HTML5 technologies and I would have to say that my experience with HTML5 video has so far been less that thrilling – at least on the desktop (great on mobile!).

Mobile – The Third Way

That leads us to mobile. So the Flash Player has gone from mobile. Not going to lose to much sleep over that as it wasn’t a very satisfactory experience and of course never going to be on the iOS. The message coming from both the event and the white paper seemed to be that retreating, retrenching, refocussing, however you want to term it, allows Adobe to “actively invest in enabling developers to create and deploy Flash based content as mobile (and desktop) applications via Adobe AIR”.

That is the crumb of consolation I take away from all of this. If I am to keep using Flash Professional, and also teaching ActionScript, then I have to know where and what kind of content should be published. Games and Video for the desktop (not Linux) fine but I also want to package up native mobile apps for Android and iOS. For me this is a killer feature of Flash Professional. Who wants to learn Objective-C right? So why doesn’t it appear as the ‘third way’ along side Gaming and Premium Video. Well, as the whole ‘Thoughts on Flash‘ saga proved the problem for Adobe is that they are hostages to Apple, and indeed Google/Android, with this killer feature. It is outside their control and could all come horribly tumbling down as I am sure they all remember it did with the launch of Flash Professional CS5. My fingers however remained tightly crossed.

JSON – Fitter, Happier, More Productive

What is JSON?

JSON is Javascript Object Notation is a lightweight way to store and move data. If you are familiar with XML think of JSON as been … fitter, happier, more productive.

So what is a Javascript object. Javascript objects consist of name : value pairs. They are defined within curly bracket as follows:


{"Author" : "Dickens"}

To list multiple name : values pairs separate them with commas as follows:

{
  "Title1": "The Adventures of Oliver Twist",
  "Title2": "The Life and Adventures of Nicholas Nickleby",
  "Title3": "The Old Curiosity Shop",
  "Title4": "A Christmas Carol",
  "Title5": "David Copperfield",
  "Title6": "Bleak House",
  "Title7": "A Tale of Two Cities",
  "Title8": "Great Expectations"
}

Hold on I thought you said JSON was fitter, happier, more productive. That looks repetitive and verbose. True and that is why we can also write JSON using arrays. Arrays are defined by square brackets.


{"name" : ["array value 1", "array value2"]}

So the above could also be represented as:

{ "title": [
"The Adventures of Oliver Twist",
"The Life and Adventures of Nicholas Nickleby",
"The Old Curiosity Shop",
"A Christmas Carol",
"David Copperfield",
"Bleak House",
"A Tale of Two Cities",
"Great Expectations"
]
}

Tip: Notice how the above can be spread of multiple lines. JSON is stickler for the syntax of curly brackets, square brackets and commas but inside an array you can format this to be more readable with lines breaks.

We see this later but what you will commonly be doing with JSON is using data provided by a third party such as Facebook or Twitter.

jQuery and JSON

We are going to use jQuery to drab some data from JSON and add it to the HTML of a document. jQuery has a function called $.getJSON. This may look a little odd compared to other jQuery you have seen like toggle():

$(".moreless").toggle(showPanel,hidePanel);

Here the toggle() method is attached to an object in the HTML DOM, in this case objects of class “moreless”. With $.getJSON it is not attached to a specific element in the DOM – it would be illogical to do so. Instead $.getJSON is a global function / method available whenever it is needed.

The $.getJSON method takes as its first argument the URL of the JSON file to load. As a second argument it takes a callback function – that is a function that will be called when the data is retrieved. Most commonly you would use an anonymous / inline function but named functions can be used as well. For an explanation of the difference between anonymous and named functions see the posted called “Anonymous / Inline vs Named Functions in Javascript”.

Assuming we have a JSON file called ‘dickens-books.json’ in the same directory as the HTML file we wish to use the data in, then using an anonymous function, we would write:


$(document).ready(function() {
	 $.getJSON('dickens-books.json', function(data) {
     // to something
    });
});

We now have the data so lets do something with it. The data is a Javascript Object so we could use jQuery’s each() method to loop around it.


<script language="JavaScript" type="text/javascript">
$(document).ready(function() {
	$.getJSON('dickens.json', function(data) {
	  var items = [];

	  $.each(data, function(key, val) {
		items.push('<li id="' + key + '">' + val + '</li>');
	  });

	  $("#myData").html(items.join("\n"));

	});
});
</script>

Here once the data is loaded we create an empty array called ‘items’. We then use $.each() to populate that array with the keys and values from the JSON data.

For more examples of each() see the post “each() To Their Own – jQuery each() Explained”.

For presentation the jQuery html() method takes the array as a string. The string is created using Javascript’s join() method. You can read more about join() in the post “Manipulating Javascript Arrays with Split and Join.

Take a look at the demo.

each() To Their Own – jQuery each() Explained

There are two flavours of each(). It can be used as selector to grab ‘each’ instance of a selector or it can be used to loop around objects like arrays.

Usage 1: Looping Elements in the HTML

We can use each() as a Selector. Assume we have a simple list:

<ul>
<li>Item</li>
<li>Item</li>
<li>Item</li>
</ul>

Then with each() we can ask jQuery to look for all the <li> elements. Now you could of course just do that with $(“li”) but each allows you to keep a count of where you are.


 $("li").each(function(i){
	$(this).append("- " + i);
});

The above targets each <li> and appends a dash and an iteration value. The resultant output is:

<ul>
<li>Item- 0</li>
<li>Item- 1</li>
<li>Item- 2</li>
</ul>

Usage 2: Arrays

Here we will use the ‘global’ version of each(). Instead of reference a jQuery object first we call each() as $.each() (like $.getJSON). The global version of each takes an object such as an array as its first parameter and then a callback function as its second. The callback function is often an anonymous / inline function for code brevity. So assume we have an array as follows:

var dickensBooks=new Array(
	"The Adventures of Oliver Twist",
	"The Life and Adventures of Nicholas Nickleby",
	"The Old Curiosity Shop",
	"A Christmas Carol",
	"David Copperfield",
	"Bleak House",
	"A Tale of Two Cities",
	"Great Expectations");

We could loop around this with $.each() as follows:

	$.each(dickensBooks, function(i, val){

		console.log("Index: " + i);
		console.log("Value: " + val);

	});

What the Dickens? The $.each() first parameter is the array. Then we have the callback function placed anonymously / inline. It takes two parameter I have called ‘i’ and ‘val’. The ‘i’ parameter will be equal to the index of our array – starting at zero. The ‘val’ parameter will be the value in that slot of the array.

We can also use Javascript objects here – Javascript Object having there name : value notation. Here is a Javascript Object:

	var dickensNovels = new Object();
	dickensNovels.title = "The Adventures of Oliver Twist";
	dickensNovels.published = 1837;
	dickensNovels.leadCharacter = "Oliver Twist";
	dickensNovels.film = "David Lean, 1948";
	dickensNovels.musical = "London, 1960"

A Javascript Object is basically an associate array. Therefore we can feed this to the $.each() lion as follows:

	$.each(dickensNovels, function(name, val){

		console.log("Name: " + name);
		console.log("Value: " + val);

	});

Please Sir, I want some more (explanation). We feed the ‘dickensNovel’ object into $.each() as its first parameter. Next along comes the inline function that takes two parameter that I have chosen to call ‘name’ and ‘value’ (call them what you will Sir). We can then loop away and extract all the goodies.

Take a look at the demo.

This particular usage of each() is often used in conjunction with data retrieved via JSON.

Anonymous / Inline vs Named Functions in Javascript

There are Anonymous - Is your Function?

With the likes of jQuery you often have the need to create callback functions. These can be anonymous / inline or named functions. Here is quick post to show the syntax differences between the two.

Anonymous

Here is an anonymous or if you prefer inline function. The function isn’t named and we get straight into the action.


$(".anon").click(function(){
	alert('I have no name!');
});

Named

Here a function is named. I called it ‘doSomethingPointless’.


$(".named").click(doSomethingPointless);

function doSomethingPointless(){
	alert('I know who I am!');
}

You can view a demo of this here.

Callbacks with Data

If you are using a piece of jQuery like $.getJSON method then your callback will have a data parameter. This can be handled anonymously or named as well. Anonymously you would do:


    $.getJSON('dickens-books.json', function(data) {
     // to something
    });

… or if you prefer not to be anonymous then:


$(document).ready(function() {
       $.getJSON('dickens-books.json', sortData);

       function sortData(data){
       // to something
      }

  });
});

Manipulating Javascript Arrays with Split and Join

Should I Split or Should I Join Now or Should I Array I Should I Go Now.

Oh dear. Shoehorning the Clash to a Javascript tutorial – phew rock ‘n’ roll.

Arrays are a neat way of moving and manipulating data. To create an array in Javascript the syntax is as follows:


var clashAlbums=new Array();
clashAlbums[0]="The Clash";
clashAlbums[1]="Give 'em Enough Rope";
clashAlbums[2]="London Calling";
clashAlbums[3]="Sandinista!";
clashAlbums[4]="Combat Rock";

Or if you prefer:


var clashAlbums=new Array("The Clash","Give 'em Enough Rope","London Calling","Sandinista!","Combat Rock");

We could reference one element of the array as follows:


clashAlbums[2];
/* would output "London Calling" */

If you a are PHP developer you’ll probably be aware of the array functions implode() and explode(). In PHP implode() turns an array into a string and explode() turns a string into an array. In Javascript join() turns an array into a string and split() turns a string into an array. Lets see these chaps in action.

The join() method of an array takes one parameter – the character you wish to use as a separator in your string. For example the following would create a comma separated list.


clashAlbums.join(",");

If we were wanting to have each item appear in HTML on a new line you could therefore use:


clashAlbums.join("<br>");

The above is not the full story as we would need to output these values. You could do that with document.write() in Javascript as follow:


document.write(clashAlbums.join("<br>"));

Alternatively you could output using jQuery by attaching the output to an element with the jQuery html() method as follows:


$("#clashlps").html(clashAlbums.join("<br>"));

You’ll find demos of both outputs here.

So that leaves split(). Split does the reverse of join() – it creates an array from a string. Take the following:


var clashAlbumsString = "The Clash,Give 'em Enough Rope,London Calling,Sandinista!,Combat Rock";

We have a string and we can use split() to convert it into an array. All we need is a suitable separator. In this example the string has been set up with commas as separators. So to convert the above string to an array we use:


var clashAlbums = clashAlbumsString.split(",");

… where ‘clashAlbums’ is the name of our array.

You’ll find a split demo here.

It has to be said in my experience join() is the more useful of the two, but it is good to know you can have two way traffic. One job where join() helps an awful lot is when you have to manipulate data that you get sent from your best mate Jason … sorry JSON.