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.

Creating Dropdown Menu Using CSS

dropdownIf you have been creating facebook applications, you know in a FBML application, the traditional javascript code is not allowed. The facebook platform has its own implementation of the javascript named FBJS (FaceBook JavaScript). The FBJS is very limited as compared to traditional javascript. So you would find yourself in trouble if you wanted to create a dropdown menu using FBJS. Now because traditional javascript is not allowed in a FBML application and FBJS is troublesome when it comes to creating menus, we will have to find some other solution to creating the dropdown menu. Well, CSS exhibits great flexibility to solve this problem. The CSS’s display property is used effectively to create the dropdown menu.

Here is the CSS code:

	/* Drop Down Menu Start */
	#container
	{
		width: 760px;
		margin:0 auto;
		font-size:11pt;
		background:#edeff4;
		font-size:12px;
		font-family:tahoma, verdana, arial;
	}
	#menu{position:absolute; z-index:1; border-top:1px solid #f6f6f6; font-weight:bold; margin-bottom:0px; left:0px; margin-left:0px; margin-top:-15px; color:#3b5898; font-size:11px; font-family:tahoma; } /* adjust margin property if needed */
	#menu ul .item{display:none;}
	#menu ul:hover .item{display:block;background:#edeff4;padding:5px;margin:1px; color:#3b5898;cursor:pointer; font-weight:normal;}
	#menu ul:hover .item a{color:#000000;text-decoration:none; font-size:11px; font-family:tahoma;cursor:pointer;}
	#menu ul:hover .item a:hover{color:#3b5898;cursor:pointer;}
	#menu ul:hover{color:#3b5898;background:#3b5898;color:#ffffff;}
	#menu ul{width:150px;float:left;margin:0px;padding:1px;background:#edeff4;list-style:none;cursor:pointer;}
	.clear{clear:both;height:10px;}
	/* Drop Down Menu End */

And here is the html code for the dropdown menu:

<div id="container" style="background:#edeff4; width:760px; position:relative; margin:auto;" align="center">
	<div id="menu">

		<ul id="item1">
			<li class="top" style="padding:6px;">Take Action &nbsp;<img border="0" align="absmiddle" src="img/drop-down-arrow.gif" /></li>
			<div align="left"><li class="item"><a href="#">My ECO Footprint</a></li></div>
			<div align="left"><li class="item"><a href="#">Reduce My Impact</a></li></div>
			<div align="left"><li class="item"><a href="#">Play Green Challenge</a></li></div>
			<div align="left"><li class="item"><a href="index.php?page=invite" style="outline:none;">Spread The Word</a></li></div>
			<div align="left"><li class="item"><a href="#">Green Ideas</a></li></div>
			<div align="left"><li class="item"><a href="#">ECO Products</a></li></div>
		</ul>

		<ul id="item2">
			<li class="top" style="padding:6px;">My Green World &nbsp;<img border="0" align="absmiddle" src="img/drop-down-arrow.gif" /></li>
			<div align="left"><li class="item"><a href="#">Check My World</a></li></div>
			<div align="left"><li class="item"><a href="#">Visit Other Worlds</a></li></div>
			<div align="left"><li class="item"><a href="#">Green Rankings</a></li></div>
			<div align="left"><li class="item"><a href="#">My Green Badge</a></li></div>
		</ul>

		<ul id="item3">
			<li class="top" style="padding:6px;">The Stores &nbsp;<img border="0" align="absmiddle" src="img/drop-down-arrow.gif" /></li>
			<div align="left"><li class="item"><a href="#">Green My World</a></li></div>
			<div align="left"><li class="item"><a href="#">Send Green Gifts</a></li></div>
			<div align="left"><li class="item"><a href="#">Get Green Coins</a></li></div>
			<div align="left"><li class="item"><a href="#">Get Carbon Reductions</a></li></div>
		</ul>

		<ul style="background:#edeff4; width:113px; cursor:default;">
			<li style="padding:6px;background:#edeff4;">&nbsp;</li>
		</ul>

		<ul id="item4">
			<div align="right"><li class="top" style="padding:6px;">About &nbsp;<img border="0" align="absmiddle" src="img/drop-down-arrow.gif" /></li></div>
			<div align="left"><li class="item"><a href="#">Global Warming?</a></li></div>
			<div align="left"><li class="item"><a href="#">About Greenbook</a></li></div>
			<div align="left"><li class="item"><a href="#">Contact Us</a></li></div>
		</ul>
	</div>

See the demo here.

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
.