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.

HTML5Sticky – Sticky Notes for the Web!

Well, yes, it has been quite a long time since I wrote the last post and that is mainly because I have been very busy at my job which didn’t allow me to write about the ideas that do come in my mind that I think I need to blog about.

Today there is a lot of buzz about HTML5 because it is really cool and a lot of front-end engineers and developers are already using it despite the fact that it isn’t fully supported by all browsers – only latest standard-compliant browsers support it, IE till version 9 does not support it and that isn’t shocking because it is “IE”, however, people have made some hacky scripts such as HTML5 Shiv to get support of HTML5 in IE. HTML5 is formally supported in version 10 of IE though. For more information about the supported features in each browser, you should head over to:

When can I use…

I have recently created a useful application using HTML5 and jQuery named HTML5Sticky. The HTML5Sticky is as the name suggests, HTML5 application you can use to create sticky notes. The sticky notes are persistent in nature meaning your created sticky notes will be there the next time you open up the app. The app uses HTML5’s localStorage feature in order to store the sticky notes.. In short, it is sticky notes for web !

Here are its features:

  • Add text and lists with basic HTML tags
  • Multiple colors
  • Customize Width and Height
  • Customize Allowable HTML tags
  • Real sticky notes look
  • Nice hand-writing-like font

You can view/download/fork the source code at github here.

And here is the demo.

HTML5Sticky featured on famous DailyJS.

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.