Archive for Javascript

Learning Javascript – the module pattern

// October 17th, 2012 // No Comments » // Development, Javascript, Web Development

A module is a self contained function, meaning that its functions and variables are private, but references to them can be returned, giving access to the internal workings via a return code block. Because of the componentisation of code, it is independently testable, can be loaded asynchronously as and when needed. What this means in human talk is described below.

The module pattern

A lot of technically rich definitions for the module pattern are out there. I however like things to be explained simply, as if a 5 year old could understand it.

Basics:

* Javascript’s variables have function scope (a variable defined in a function is not directly available from outside the function).
* Functions are data, and objects at the same time (functions can contain other functions).
* Functions can be self calling by appending a set of (). This would essentially call itself.

From the above we can see that if we define a function within a function, and set a return value of references to these functions or variables, we can create private functions and variables.

For example:

var myIncrementer = function () {
var i = 0;
function increment() {
return ++i;
}

return {
inc: increment
}

}();

So what happens here is first is that myIncrement is assigned the return value of the anonymous function, which itself is a reference to the private function of increment. when you call the inc() function, the private variable i is incremented and returned.

Now also notice something, the value saves its state too. This is called a closure. Another great thing about this pattern is that you can refer to the internals of the package directly.

Hide email addresses with ISO Characters

// March 17th, 2010 // No Comments » // Development, Javascript, XHTML

Putting email addresses on websites is easy pray for screen scraping spam monserts. There are various techiques out there such as using graphics instead of text, or using javascript. The technique I like is to convert individual characters in an email address into ISO characters. Einstein once said that never memorise anything you can look up in a book, so I don’t want to walk around with ISO character numbers in my noggin. I created this little tool to convert email addresses into ISO codes. Just put in your email address. It will prefix your email with a “mailto:” too.




Opening a browser in a new window

// February 5th, 2010 // No Comments » // Development, Javascript, JQuery, XHTML

For a long time target=”blank” has been redundant for accessibility problems. However, there are situations when opening a new window is neccessary. One technique I used is attaching a class of “external” to each link, and then usung javascript descibed in my get elements by class name example, attach a “window.open(this.href)” to each one. I now use JQuery, so that code has been superceded with just 2 lines of JQuery code.

Link Relationships

Links are used to locate web resources, so good use of the rel attribute enhance the logic and semantic meaning of these resources. Using the rel attribute for things such as pagination i.e. “next” and “prev” are standard link types, so where does “external” fit into this?

You can define additional link types not described in the specification. If you do you should use a profile to cite the conventions used to define the link types. You do this in the meta data profile attribute of the HEAD element:

1
<head profile="http://www.yoursite.com/profiles/core">

You can either use XML for this, or XHTML. A good XHTML example can be found at gmpg.org and at w2.org. As for an XML example, I can’t find one.

Styles and Accessibility

From an accessibility point, you should differentiate external links by some sort of style or description such as (opens new window). So, in order to do that you might want to add a class of external anyway.

JQuery

The actual code in JQuery is very concise. For each a tag with a rel of external, a new window will be opened:

1
2
3
4
5
$('a[rel="external"]').click(function()
{
	window.open(this.href);
	return false;
});

Firebug in Chrome, IE, Safari, Opera?

// January 8th, 2010 // No Comments » // Development, Javascript, Web Development, XHTML

I love Firebug. I wouldn’t say it makes debugging a pleasurable experience, but it makes it a hell of a lot easier than if you didn’t have it. This is fine when you are working explicitly in Firefox, but what happens if you need to debug something in other browsers? Nightmare. IE has the developer plugin, but if I love Firebug, I hate IE developer plugin (I won’t say how much I hate explorer though tee hee). So, what’s a guy to do? Firebug lite . Firebug lite is a JavaScript file you insert into your pages to simulate some Firebug features in browsers other than “Firefox”. This will be really handy!

Google Event Tracking

// November 6th, 2009 // No Comments » // Development, Google Analytics, Javascript, JQuery

I was asked recently if there was any way to track click events on an accordion we have implemented on a site. When first asked I didn’t think this was possible without an awful lot of javascript. However, a colleague mentioned Google event tracking is already available in Google if you have the standard setup. You can attach various events on various elements. The example on the google site is attaching the event to a play button.

Event tracking is so simple to impliment. You don’t even have to set anything up within anaylitics, you simply add the tracking event, and when events happen, this will be recorded. The format for the event is:


_trackEvent(category, action, optional_label, optional_value)

To impliment it using JQuery, I simply added a click event to the element like this:

1
2
3
4
5
6
7
$('#accordion h3 a').click(function()
{
	//get the section title
	var section_title = $(this).text();
	//call pageTracker and track the event
	pageTracker._trackEvent("recipes", "click", section_title);
});

Simple!

Get elements by class name with javascript

// May 14th, 2009 // 4 Comments » // CSS, Javascript

Javascript does not support getting elements by class name; it only allows you to get elements by id. It is very useful having the ability to do this however, such as opening windows on a click when an anchor has an “external” class attached to it. As I don’t use frameworks such as JQuery for everything, I created this function which gets each element with a given class name and returns an array of each element.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
document.getElementsByClassName = function(className)
{
  var children = document.getElementsByTagName('*') || document.all;
  var elements = new Array();
  for (var i = 0; i < children.length; i++)
  {
    var child = children[i];
    var classNames = child.className.split(' ');
    for (var j = 0; j < classNames.length; j++)
    {
      if (classNames[j] == className)
      {
        elements.push(child);
        break;
      }
    }
  }
  return elements;
}

Javascript Body Mass Index Script

// February 13th, 2009 // No Comments » // Development, Javascript

I was recently playing with some JavaScript which calculates your BMI or body mass index. It is just a small bit of code and I didn’t want to use any frameworks. Obviously I want to use the DOM and have no intrusive code.

There are two calculations to BMI. One is using the metric system the other using the imperial system.

For the imperial system the formula is:

1
(weight-in-pounds  *  703) / (height-in-inches * height-in-inches)

For the metric system the formula is:

1
(weight-in-kilos) / (height-in-meters * height-in-meters)

Getting the values of the form select box and text boxes is done using document.getElementById. As these are text values I used parseInt() in order to do arithmetic with the values.

Once the totals were found I wanted to round the values to 2 decimal places using Math.round(bmi*100)/100;

Instead of an alert box to give the results I created an empty div as I wanted to set the content of it dynamically. I gave an id to the div of “results”. I first create a reference to the DOM node. Once you have this you can remove any of the child nodes using node.removeChild(node.childNodes[0]). If you don’t do this, each time the script is called the message will be appended to the last one. Now there are no children, you can add one using document.getElementById(“results”).appendChild(textnode).

1
2
3
4
var node = document.getElementById("results");
node.removeChild(node.childNodes[0]);
var textnode = document.createTextNode(result);
document.getElementById("results").appendChild(textnode);

Here is the code in full:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function get_bmi()
{
	var bmi = 0;
	var system = document.getElementById("system").value;
 
	if(system == "standard")
	{
		var inches = parseInt(document.getElementById("inches").value);
		inches += parseInt(document.getElementById("feet").value) * 12;
		bmi = (document.getElementById("pounds").value * 703) / (inches * inches);
	}
	else if (system == "metric")
	{	
		var meters = document.getElementById("centimeters").value / 100;	
		bmi = document.getElementById("kilos").value / (meters * meters);
	}
	bmi = Math.round(bmi*100)/100;
	result = "Your BMI is " + bmi;
	var node = document.getElementById("results");
	node.removeChild(node.childNodes[0]);
	var textnode = document.createTextNode(result);
	document.getElementById("results").appendChild(textnode);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
function show_hide()
{
	if(document.getElementById("system").value =="standard")
	{
		document.getElementById("standard_div").style.display = "block";
		document.getElementById("metric_div").style.display = "none";
	}
	else
	{
		document.getElementById("standard_div").style.display = "none";
		document.getElementById("metric_div").style.display = "block";
	}
}

Here is the working script: