JavaScript Best Practices

JavaScript is not only amazing language but also very tricky language. To make correct use of it, you need to follow some best practices to avoid any problems that might come about otherwise. I share some of the best practices you really should be following when writing JavaScript code. Of course this is not an exhaustive list but at the most fundamental level, every programmer should know and adhere to it.

1 -NEVER FORGET VAR KEYWORD

Most of the developers know about this but yet I wanted to mention this because it may not be clear to some or newbies or people having other programming language background that come to JavaScript.

Consider the following piece of code:

function myFunc(){
var firstName = 'sarfraz';
lastName = 'ahmed';
}

It should be noted that in JS, variables have function-level scope which means a variable declared inside a function can not be accessed outside of it. So let’s test above two variables:

myFunc();
console.log(lastName); // ahmed
console.log(firstName); // undefined

As you will notice, we are still able to access lastName variable. The reason is that it does not have function-level scope because we forgot to put var keyword before it unlike firstName variable. Hence, lastName variable went into global scope and became part of window (while inside browser) object eg window.lastName will output the last name too.

It is therefore always required to put var keyword before variables so that they do not become part of global scope. It has following benefits:

  • You save the memory and improve performance
  • You don’t pollute the global scope
  • You mistakenly don’t overwrite a global variable that might have the same variable name

This is a very important concept and JS developers have always been finding solutions to avoid this problem. One of the most popular solution is Singleton or Module Pattern you should check out. By the way, if you want to see other patterns also, take a look at:

Essential JavaScript Design Patterns For Beginners

2 – DECLARE VARIABLES ON TOP

Another thing that should be followed is that variables should be declared on top of each function because of what is known as JavaScript Hoisting. Here is an example:

var name = 'sarfraz';

(function(){
console.log(name); // undefined
     var name = 'nawaz';
     console.log(name); // nawaz
})();

Notice that even though name variable is outside the scope of function but on the very fist line it gives back undefined rather than actual name. The reason for this is that interpreter hoists or moves variables on top of the function, here is how interpreter sees or re-arranges it:

var name = 'sarfraz';

(function(){
     var name;
     console.log(name); // undefined
     name = 'nawaz';
     console.log(name); // nawaz
})();

As can be seen, name variable has been hoisted to top and declared there and also var keyword has been stripped from it where we assigned the value of ‘nawaz‘.

The same is issue is not only with variables but also function declarations but NOT with function expressions. You can learn more about the difference between function declaration and function expression here:

Named Functions Demystified

The solution to this problem is to always declare variables and function declarations on top of container function:

function myFunc(){
     var foo;
     var bar;
     var baz;

     // do something foo, bar, baz
}

The preferred and recommended syntax though that you must follow is to declare all variables in one go by separating them with a comma:

function myFunc(){
     var foo, bar, baz;

     // do something foo, bar, baz
}

3 – INITIALIZING MULTIPLE VARIABLES

Declaring variables on top is good practice but not multiple initialization. Consider:

function myFunc(){
var lang = encoding = 'en';
}

This is a very common mistake even amongst experienced JS developers where they think they have quickly assigned two variables same scope and same value. Though value for both lang and encoding variable is some but not the scope. Try it out:

myFunc();
console.log(encoding); // en
console.log(lang); // undefined

Here again, variable encoding has gone into global scope. Since var keyword is only appears before lang variable, that is the one which gets correct functional scope. In short, you should avoid that shorthand initialization unfortunately.

4 – STARTING CURLY BRACE ON THE SAME LINE

Consider the following code block where starting curly brace “{” is on a new line, this works fine in most situations.

function myFunc()
{
// some code
}

However, same convention will not yield expected results if you happen to write:

function myFunc()
{
     return
     {
         name: 'sarfraz'
     };
}

var f = myFunc();
console.log(f);

The result will be undefined because behind the scenes, interpreter puts a semicolon ‘;‘ after the return keyword making it:

function myFunc()
{
     return; // <----------------
     {
         name: 'sarfraz'
     };
}

To remedy such hard-to-debug issues, it is good practice to always put starting curly brace on the same line, this would work fine though:

function myFunc() {
     return {
         name: 'sarfraz'
     };
}

var f = myFunc();
console.log(f.name); // sarfraz

And that’s a reason why Douglas Crockford in his book “JavaScript: The Good Parts“, advocates this syntax for JS:

function () {
     // some code
}

if (expression) {
     // do something
}

Go ahead and check out JavaScript Coding Style to learn more as well as naming conventions.

Notice that it is not the return keyword affected by automatic semi-colon insertion but all these too:

  • var statement
  • empty statement
  • expression statement
  • do-while statement
  • continue statement
  • break statement
  • throw statement

Experienced JavaScript developers know pretty well about JavaScript’s automatic semi-colon insertion problem and avoid it. The benefit of above coding style however is that you avoid this problem without knowing that this problem exists just by following that coding style.

5 – USE ARRAY LITERAL INSTEAD OF NEW ARRAY()

There are two ways you can create arrays in JS:

var arr1 = new Array(); // array constructor
var arr2 = []; // array literal

Though both serve the purpose of creating arrays but there is important difference between the two.

In JS, even an array is an object. With first constructor method above, you are telling interpreter to call constructor of the Array and generate an object. The interpreter looks up into the execution context to find the constructor and once found, it calls it and creates the Array object. It seems that it has performance hit too as compared to latter array literal method. With the array literal method, interpreter just creates the array on run-time with no extra processing done.

Other than that, Array constructor is mis-guiding the way it handles its parameters. Consider:

console.log(new Array(5)); // [,,,,]
console.log(new Array('5')); // ["5"]

When one argument is passed to Array and that happens to be a number, a new array is returned with its length property equal to that number passed. The important thing to note here is that Array will be initialized from what number you specified to it, for example:

// Array constructor
var arr = new Array(2);
console.log(arr.length); // 2
console.log(arr[0]); // undefined

// Array literal
var arr = [2];
console.log(arr.length); // 1
console.log(arr[0]); // 2

So the conclusion is to always use array literal notation rather than Array constructor.

6 – USE PROTOTYPE TO SHARE ACROSS

The concept of prototypes or prototypal inheritance is rather confusing. I have seen people especially inexperienced JS developers adding class members to parent function which needs to be shared across child classes. Consider the following code:

function Person(name){
this.name = name;
}

Now let’s assume we want to have child classes the ability to display the names some how, one of doing it is putting method directly inside Person class:

function Person(name){
     this.name = name;

     this.display = function(){
         alert(this.name);
     }
}

Other way is to use prototype:

function Person(name){
     this.name = name;
}

Person.prototype.display = function(){
     alert(this.name);
}

With both ways, all child classes will be able to use the display method but there is important difference between the two. When you attach any methods or properties via this (first way above) to a class then all instances of inheriting child classes will also have these properties or methods within them or their signature. On the other hand, when you use prototype to add members (properties and methods) to parent class, children classes will still inherit all members but it won’t be present inside their own functionality or signature, rather they will be borrowing that functionality from their parent class thereby saving memory. For this reason, later approach seems good to follow in most situations.

7 – PUT COMMA BEFORE PROPERTIES

When working with objects or arrays, it is always a good idea to put a comma before the variable or object property eg:

// jQuery - create a new div with some css
$('</pre></pre></pre>
<div>').attr({</div>
<pre>
<pre>
<pre>
 "id" : "myId"
 , "class" : "myClass"
 , "class" : "myClass"
 , "color" : "green"
 , "fontWeight" : "bold"
});

In this way, we never add an extra comma or forget one from the last property. The reason why this is good practice is that, in IE, with extra comma at the last property, we do not get expected results sometimes (ExtJS developers must have learned this). I do the same with multiple variable declarations or arguments of function. It also makes the code look pretty too as far as I see it.

8 – DON’T MIX JS AND HTML

One of the most important best practices is to always separate JS code from HTML and go unobtrusive. One would often see code like this:

<a href="#" onclick="doSomething()">Some Action</a>
<input type="button" onclick="doSomething()" value="Do Something" />
<form onsubmit="doSomething();">...

That’s a very bad practice in that it is hard to manage and maintain. HTML and JS should not be mixed ever. You could do the same thing like this:

<a href="#" id="link">Some Action</a>
<input type="button" id="button" value="Do Something" />
<form id="frm">...

<script type="text/javascript">
var link = document.getElementById('link'),
 btn = document.getElementById('button'),
 frm = document.getElementById('link');

link.onclick = function(){
 // do something
};

btn.onclick = function(){
 // do something
};

frm.onsubmit = function(){
 // validate form
};

</script>

This way it becomes easy to manage, maintain or enhance both HTML and JavaScript.

9 – PUT SCRIPTS AT BOTTOM

Normally scripts are put in <head></head> tags but this should be avoided. The reason for this is that browser loads your scripts sequentially and by the time they are loading, nothing else is done and website load times slow down (or at least that’s how visitors will perceive it) and you see actual output only after those scripts have been loaded by the browser.

The best practice is that scripts should be put on bottom of page just before closing body tag eg </body>. This way browser will instantly display page and page load time will be better for users who view that page.

By the way, always put CSS on top in <head></head> tags because that’s something browser reads first and renders page’s layout accordingly.

Read more about this at famous Yahoo’s performance article.

I would also suggest you to use Yahoo’s YSlow or Google’s PageSpeed add-on (add-ons of Firebug) which suggest you a lot of things on how to improve the performance of the page.

10 – NEVER FORGET SEMI-COLON

Always end statements and function expressions with a semi-colon:

var name = 'some name'; // <-------------

var myFunc = function(){
// some doe

}; // <------------

This is useful when you want to compress the code (for faster load times). If at any place, semi-colon isn’t present, you won’t be able to compress the code or wouldn’t get expected results most likely code-wise. You should always, always use semi-colons.

BONUS

The good news is that you can solve most of above problems by using JSHint or JSLint code quality tool. It will tell you about best-practices and any errors that might exist in your code. Having said that, it is good to improve your JS skills and avoid the need to go to such tools.

Learning Javascript

JavaScript is cross-platform, cross-browser language; javascript is everywhere; web, RIA (rich internet applications), mobile, tablets, animations and even on server with the advent of node.js. Javascript is the language of the future.

I started off with jQuery without knowing anything much about javascript because by the time I didn’t find any reason to learn it due to fact that  javascript libraries did everything we needed putting complexities out of the way. Today I realize that I chose the wrong path, a good understanding of javascript language is crucial if you look at the reasons I have mentioned in the very beginning but it is never too late to start again, that’s exactly what I have decided, learning javascript seriously. I am not the only one who has started realizing the power and future of javascript, there are giants who have started learning it too. If you are also javascript-library-only developer, or even copy-paster programmer, you should really learn javascript !

Despite design flaws and bad reputation of the language as they say and probably rightly so, javascript is popular and language of the choice for those who have gone into deeper understating of it. Javascript language does have bad parts but its good parts over-weigh its bad parts and there is always room to avoid bad parts if you know the language right and use it effectively.

Javascript turns out to be extremely tricky language, consider:

// Comparison
'' == '0';    //false
0 == '';    // true
0 =='0';    // true

// Type checking
typeof null;    // object

// Scope
function myFunc() {
  return
  {
    name: 'sarfraz'
  };
}

var f = myFunc();
console.log(f);    // undefined

I did a lot of research to find best javascript learning resources. On the journey of my exploration, I came across some of the great resources with a lot of reviews and user feedback. By now, if you made your mind to take javascript seriously, here are the best resources out there you should check out.

Books

Online

Videos

Blogs to Subscribe

Tools

Let’s start… :)

Javascript Self Invoking Functions

In this article, I will discuss self-executing or self-invoking functions of javascript and their hidden power with real-world example. We will also see why using setInterval is bad in some situations and should be avoided. Let’s explore little used but extremely powerful self-invoking functions of javascript.

Self-Invoking Anonymous Function

A self-invoking anonymous runs automatically/immediately when you create it and has no name, hence called anonymous. Here is the format of self-executing anonymous function:

(function(){
 // some code…
})();

You must be aware of the fact that javascript functions run immediately when you put () after their names eg:


doStuff(); // this will run immediately

And:


doStuff; // this will not run immediately and can be used as callback

Now because () exist at the end of self-executing anonymous function above, it will run immediately.

Interestingly, if you look at the source code of jQuery, you will see that everything is wrapped in between:

(function( window, undefined ) {
 // jQuery code
})(window);

That is as can be seen also a self-executing anonymous function with arguments. A window (and undefined) argument is created and is mapped with global window object at the bottom (window).

Notice that you can also write self-executing anonymous function like this:

(function(){
 // some code…
})();

Using extra braces like before function keyword is simply coding convention and is used even by famous javascript libraries such as jQuery and also recommended by Douglas Crockford. If you are confused about that extra pair of braces, here is another easy to remember notation:


! function(){
// some code…
}();
Notice the addition of ! before function keyword, it is essentially same in functionality to previous notation and also recommended (used by twitter too), quoting docs, section 12.4:
An ExpressionStatement cannot start with the function keyword because that might make it ambiguous with a FunctionDeclaration.

Self-Executing Function

Self-Executing function is a named function that runs immediately. Example:


(function foo(){
 // some code…
})()

Notice that now that we have named our function foo, it is not an anonymous function though it still is self-executing function because of () at the end.

How do they run automatically?

This can be best explained through an example. Let’s say in your webpage you have this javascript code:


function showUp(){
 alert(’Hello There’);
}

When you visit the page, the showUp function will not get triggered unless you do so by calling the function:


function showUp(){
 alert(’Hello There’);
}

// run the function
showUp();

However, you can make the function auto-run by making it self-executing function like this:

(function showUp(){
alert(’Hello There’);
})()

Where to use self-executing functions?

One obvious situation is when you want to auto-run a function like I showed in above example but that is trivial. If you are in a situation where you want to run a piece of code repeatedly like updating something in the database based on user interaction or fetching records from database every 10 seconds or you want to load new stories via ajax similar to how facebook does on its homepage or some other similar situation, one would normally go for setInterval function something like this:

setInterval(doStuff, 10000);

Above, doStuff function will get called every 10 seconds. That is the normal approach most developers seem to go with. However, there is a huge problem with that. The setInterval will call doStuff function exactly at specified time of 10 seconds again and again irrespective of whether doStuff function actually finished doing what it is supposed to do. That is bad and will certainly get you into unexpected results.

That is one example of where setInterval is ^bad^ and should be avoided.

This is exactly where self-executing functions come in handy. We can do the same task with the help of self-executing function along with setTimeout like this:

! function foo(){
 // your other code here

setTimeout(foo, 10000);

}();

This code will also repeat itself again and again with one difference. setTimeout will never get triggered unless doStuff is finished. A much better approach than using setInterval in this situation.

You can see the example in action here.

Another more common use of self-invoking functions is data privacy, everything wrapped in them is only available within the scope of these functions.

Rotate and Fly off elements with jQuery and CSS3

In this post, we will look at how we can use CSS3’s property transform and other vendor-specific properties to rotate elements and finally fly them off the page with jQuery. We will also use setInterval function of javascript for the continuous animation or rotation of the elements. So let’s get started with it.

Rotating Elements

To transform/rotate elements, there is a CSS3 property transform, here is the syntax of it:

transform: rotate(Xdeg)

Where X can be any number denoting the amount of rotation/angle. For example:

transform: rotate(90deg)

Any element applied above rule, will transform to 90 degrees.

Continuous Rotation

To rotate elements continuously, we can use the setInterval function of javascript along with some math. Check out the demo below:

Rotating Elements with jQuery & CSS3

The code of interest for the rotation is as follows:

$('.rotate').click(function(){
	var interval = null;
	var counter = 0;
	var $this = $(this);
	clearInterval(interval);

	interval = setInterval(function(){
		if (counter != -360) {
			counter -= 1;
			$this.css({
				MozTransform: 'rotate(-' + -counter + 'deg)',
				WebkitTransform: 'rotate(' + -counter + 'deg)',
				transform: 'rotate(' + -counter + 'deg)'
			});
		}
	}, 10);
});

Here I assume you know the basics of jQuery like ready handler, class and id selectors, etc. I have explained those things in my other posts, so I won’t be discussing them but instead I will concentrate on the part of the code which is responsible for the rotation.

First of all, we assign a click handler to each element with the class of rotate. Later we create the necessary variables including $this equalized to $(this) meaning the current clicked element, this is useful because we will reference this variable later in the setInterval function. As an element gets clicked, we also stop the current animation or clear the time interval using clearInterval function.

Later inside setInterval function, we decrement the variable counter by one with each 10th Milli-second passed (the second argument specified to the setInterval function). I have specified lesser time so that animation is little faster. The reason why I decrement the value of counter is that I wanted to rotate the elements in anti-clock-wise direction. This variable keeps on decreasing until it reaches -360 specified above in the if condition meaning that our element has rotated completely and has come back to its original place.

Now since we have put transform CSS3 property in the setInterval function and $this refers to current clicked element, the element starts rotating with continuous animation because counter variable has been specified as the degree of rotation:

transform: 'rotate(' + -counter + 'deg)'

Note that MozTransform and WebkitTransform are vendor-specfic CSS3 properties of Mozilla and Webkit (Chrome and Safari) browsers.

I have also created javascript version of rotating elements which can be seen here:

Rotating Elements with JavaScript & CSS3

So that is all there to rotating the elements in continuous fashion. Next we will see how with slight modification we can fly the elements off the page.

Flying Elements Off the Page

To fly elements off the page, we use jQuery’s animate method like this:

animate({left: '+=' + counter + 'px'}, 40);

That one single line is needed to fly off elements off the page, we add this line to our previous code just after we applied CSS3 properties like this:

$('.rotate').click(function(){
	var interval = null;
	var counter = 0;
	var $this = $(this);
	clearInterval(interval);

	interval = setInterval(function(){
		if (counter != -360) {
			counter -= 1;
			$this.css({
				MozTransform: 'rotate(-' + -counter + 'deg)',
				WebkitTransform: 'rotate(' + -counter + 'deg)',
				transform: 'rotate(' + -counter + 'deg)'
			}).animate({left: '+=' + counter + 'px'}, 40);
		}
	}, 10);
});

It is time to check out the demo:

Fly Off Elements with jQuery & CSS3

Here, we have basically specified left property of CSS to the animate method so that elements flies away to the left. You could also specify top to fly elements away to to the top. In fact, you could specify many other CSS properties to animate method such as width, height, margin, etc. Generally, you can specify any CSS property to animate method that can be specified in pixels values or in other words that could be increased or decreased.

Now that we have seen how to rotate elements and fly them off, it is up to you how you can take the idea and use in your cases. I suspect there could be  quite some ways we can use this technique effectively. I might come up with something fancy in my future posts while using this technique. As a last example, here is one idea to delete elements while flying them off the page:

Deleting Elements while Flying them off the Page

Browser Compatibility

The transform property works in all modern and standard-compliant browsers. It does not however work in IE, however there exist alternative when it comes to IE which is using IE-specific transformation filters you might want to consider for the rotation purpose. Here is IE-specific example:

#myElement {
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=2);
}

The value for the rotation can be either 1, 2, 3, or 4. Those numbers represent 90, 180, 270, or 360 degrees of rotation respectively.

There also exists cssSandpaper, the CSS3 Javascript library comes in handy when you want transformations to work across all browsers.

I hope you came to know about something useful you can put to use in your own ways.

Custom Facebook Connect Image

One of the ways you can put facebook connect button on your site is to use <fb:login-button> fbml tag something like this:

  <fb:login-button onlogin="window.location='www.example.com'"></fb:login-button>

That will show default facebook button with a rather small image. You can make the button little larger by specifying length and size attributes like this:

  <fb:login-button onlogin="window.location='www.example.com'" length="long" size="large"></fb:login-button>

However, the requirement in my case was that the button should be even bigger. I searched through the facebook connect docs and elsewhere but did not find a way to customize the facebook connect image (it is rendered directly by facebook; let me know if there is a way via comments please). I thought why I can’t force the facebook connect button to use the image that I specify. I fired up firebug (the addon of firefox) and this is what it showed for the <fb:login-button> fbml tag:

As can be seen, facebook automatically applies FB_login_button class amongst others to the connect button. As you can see, there is an img tag inside, that was all I needed to get my own image for the connect button. The idea is to find the image inside connect button and replace with your own once DOM has loaded. Now you get the idea, I wrote this jQuery code to get custom image for the connect button:

<script type="text/javascript">
$(function(){
  // overwrite the fb connect image - let's force it !!
  $('.FB_login_button').find('img').attr('src', 'img/my-custom-image.png');
});
</script>

We use the selector .FB_login_button and then use find method to find the image inside element (<fb:login-button>) having that class and replace its src attribute with the path of our custom image.  Since we have wrapped our code in ready handler $(function(){…}), our code will execute as soon as DOM becomes ready and when you visit the page, it will have your own custom facebook connect button image.

I also noticed that there was a link tag generated with the class of fbconnect_login_button. We could use that just as well like this:

<script type="text/javascript">
$(function(){
  // overwrite the fb connect image - let's force it !!
  $('.fbconnect_login_button').find('img').attr('src', 'img/my-custom-image.png');
});
</script>

Now this is good as long as you are using jQuery on the page where facebook connect button exists. But if you are not using jQuery, you can do the same thing with vanilla javascript albeit with little more code. Here is how you can do the same thing with vanilla javascript:

<script type="text/javascript">
window.onload = function(){
  var ourImg = null; // this will store the facebook connect img tag

  // find all the links on the current page
  var links = document.getElementsByTagName('a');

  // loop over all the links
  for(var i = 0; i < links.length; i++){
    // get class of this link
    var cls = links[i].className;

    // check to see if this is the link with specified class
    if (cls === 'fbconnect_login_button'){
      ourImg = links[i].firstChild; // which is img tag we need
      break;  // done, let's get the hell out of here
    }
  }

  // finally replace with our own image !
  ourImg.src = '<?php echo base_url() ?>images/fb.png';
};
</script>

Ops ! that is a lot of code I have written compared to jQuery’s but that’s what you need if you are not using jQuery on your page. Note that this time, we are using load event of the window window.onload = function(){…} which will fire when all the page resources are loaded including images, frames and the DOM unlike ready handler of jQuery which fires as soon as DOM becomes ready and runs before images, frames or any other external resources loaded into the page.

Finally, this is the page that now uses custom facebook connect button image while using <fb:login-button> fbml tag:

View the Page

Javascript: Active Content

If you look at any solution involving tabs, you will notice two things:

  • When you click on a tab, content is grabbed through ajax for the clicked tab.
  • Or it is made visible which was previously hidden.

As you might have guessed, it is better to go with the later approach because for the interface involving tabs, ajax doesn’t seem to be logical or fast solution. You click on a tab, content should be visible at the same time.

Well, the idea for the solution is simple:

You put all your content within the document inside some containers like DIVs and giving each DIV a unique ID which javascript needs to load the correct content based on the tab clicked. Also, you make the content for the first tab to be visible when page is loaded and hide rest of the DIVs. Finally, you use javascript to do the trick.

I have made a generic javascript solution that you can import into your page and use it straight away. Here is what you need to do to make your content always active:

  • Import the active content JS file into your file:
<script type="text/javascript" src="active_content.js"></script>
  • Where you generate your tabs, put links like this:
	<a href="#" onclick="show_content('div_1'); return false;">One</a>
	<a href="#" onclick="show_content('div_2'); return false;">Two</a>
	<a href="#" onclick="show_content('div_3'); return false;">Three</a>

As an example, when above links are clicked, they will show below divs:

	<div align="center" id="div_1" class="active_content">

		<h3 style="color:#FF0000;">Div One</h3>
		<p style="width:400px;">
			Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
			Vivamus non risus. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
		</p>
	</div>

	<div align="center" id="div_2" class="active_content">
		<h3 style="color:#FF0000;">Div Two</h3>
		<p style="width:400px;">

			Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
			Vivamus non risus. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
			Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
			Vivamus non risus. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
			Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
			Vivamus non risus. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
		</p>
	</div>

	<div align="center" id="div_3" class="active_content">
		<h3 style="color:#FF0000;">Div Three</h3>
		<p style="width:400px;">
			Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
			Vivamus non risus. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
			Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
		</p>
	</div>

Here is the active content javascript code:

//////////////////////////////////////////////////////////////////
//	- ACTIVE CONTENT -											//
//////////////////////////////////////////////////////////////////
//	Created By ;												//
// 	SARFRAZ AHMED CHANDIO										//
//	sarfraznawaz2005@gmail.com									//
//																//
//	Create Date: 30 Jan 2009									//
//	Last Update Date: N/A										//
//////////////////////////////////////////////////////////////////
//	Please keep this notice intact if you are using this file.	//
//////////////////////////////////////////////////////////////////

	addLoadListener	(init_dynamic_tabs);

	function init_dynamic_tabs()
	{
		var items = getElementsByAttribute("class", "active_content");
		var counter = 0;
		for (var i = 0; i < items.length; i++)
		{
			counter++;
			// make all items invisible except for the first one
			if (counter != 1)
			{
				items[i].style.display = "none";
			}
		}
	}

	function show_content(id)
	{
		var items = getElementsByAttribute("class", "active_content");

		// hide all items
		for (var i = 0; i < items.length; i++)
		{
			items[i].style.display = "none";
		}

		// show required item now
		document.getElementById(id).style.display = "block";
	}

	/* Very useful function for getting elements by their attributes */
	function getElementsByAttribute(attribute, attributeValue)
	{
	  var elementArray = new Array();
	  var matchedArray = new Array();
	  if (document.all)
	  {
		elementArray = document.all;
	  }
	  else
	  {
		elementArray = document.getElementsByTagName("*");
	  }
	  for (var i = 0; i < elementArray.length; i++)
	  {
		if (attribute == "class")
		{
		  var pattern = new RegExp("(^| )" +
			  attributeValue + "( |$)");
		  if (pattern.test(elementArray[i].className))
		  {
			matchedArray[matchedArray.length] = elementArray[i];
		  }
		}
		else if (attribute == "for")
		{
		  if (elementArray[i].getAttribute("htmlFor") ||
			  elementArray[i].getAttribute("for"))
		  {
			if (elementArray[i].htmlFor == attributeValue)
			{
			  matchedArray[matchedArray.length] = elementArray[i];
			}
		  }
		}
		else if (elementArray[i].getAttribute(attribute) ==
			attributeValue)
		{
		  matchedArray[matchedArray.length] = elementArray[i];
		}
	  }
	  return matchedArray;
	}

	// this will run the specified function on document load
	function addLoadListener(fn)
	{
	  if (typeof window.addEventListener != 'undefined')
	  {
		window.addEventListener('load', fn, false);
	  }
	  else if (typeof document.addEventListener != 'undefined')
	  {
		document.addEventListener('load', fn, false);
	  }
	  else if (typeof window.attachEvent != 'undefined')
	  {
		window.attachEvent('onload', fn);
	  }
	  else
	  {
		var oldfn = window.onload;
		if (typeof window.onload != 'function')
		{
		  window.onload = fn;
		}
		else
		{
		  window.onload = function()
		  {
			oldfn();
			fn();
		  };
		}
	  }
	}

Proceed to download the Active Content.

CValidate – Cool Javascript Validation

cvalidateI have created the CoOl javascript validation which provides you with an automated inline form validation using Document Object Model (DOM). The script has built-in checking of patterns such as email, date, alpha, text, number, decimal and url and regex. So the field you want to apply these patterns to should be a required field first.

In order to activate the validation for an element, all you have to do is to put the keyword required in the class attribute and also set the title of the element (which will appear in validation box) in the title attribute. Finally, just place return validateForm(‘myform’) in the onSubmit event of the form where myform is the id of the form being validated.

Have a look at the demo.

You can download it here.

.
tweet_this
.