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.

jQuery Drop Shadow Plugin Revisited

In one of my previous posts, I had shown how to create jQuery drop shadow plugin. To create the drop shadow effect, I was basically creating a div behind the elements which were to be shadowed. I knew about CSS3 box-shadow property but I did not consider it for the drop shadow effect because CSS3 is only supported by modern standard-compliant browsers but a comment of C-King at my previous post made me rethink about it and in this post, the plugin has been modified to create the CSS3 drop shadow effect.

The plugin now applies CSS3 drop shadow effect for the browsers that support it or it will use div-based approach like it did before. The plugin now checks if the current browser supports CSS3 and if so, it will apply CSS3 drop shadow effect and if CSS3 is not supported, it will apply div-based drop shadow effect. A new blur option has been added into updated plugin which is only applicable if current browser supports CSS3.

The plugin has been checked working fine in IE6+, FF, Webkit and Opera.

Download Drop Shadow Plugin (Updated)

StyleTable jQuery Plugin

While working on a project few days back, I came upon a requirement to make html tables look pretty and for that I created a function in jQuery to style a table by calling that function on a given table. Later I thought of converting that function into more usable piece of code – a jQuery plugin and I introduce the StyleTable jQuery plugin.

.

.

.

Using the plugin is as  simple as this one line of code:

  $('table').styleTable();

Off course,  you can also apply the StyleTable plugin based on table classes or ids or even their attributes. See the plugin documentation for more information and examples.

See the plugin in action along with documentation

Download TableStyle Plugin With Examples

.

Creating Drop Shadow jQuery Plugin

In this article, we are going to create a very useful jquery plugin, the Drop Shadow plugin. Previously, I had written an article on how to create the drop shadow effect and today we will use that code and convert it into a plugin. Here is the code we were using previously to apply the drop shadow effect to elements having shadow class:

$(window).load(function(){
	$('.shadow').each(function(){
	  $('</pre></pre>
<div>').appendTo($('body')).css({</div>
<pre>
<pre>
		position: 'absolute',
		width: $(this).width() + 'px',
		height: $(this).height() + 'px',
		backgroundColor: '#DFDFDF',
		zIndex: -5000,
		top: ($(this).offset().top + 5) + 'px',
		left: ($(this).offset().left + 5) + 'px'
	  });
	});
});

If you have been using jQuery but have never created a plugin before, you may ask why create a plugin at all. Well, there are some good reasons why not create a plugin.

How to Create a Plugin

First of all, we should make sure that we name our plugin as per standards, a jquery plugin should be named like:

jquery-pluginName-plugin.js

And since our plugin is going to be used for dropping shadows on elements, it should be named:

jquery.dropshadow.plugin.js

Now creating a jquery plugin isn’t a much of problem, the creators of jquery have made things really easy for us to create the plugins. In fact, creating a jquery plugin is as easy as:

$.fn.pluginName = function(){
   // code here....
}

However, there do exist quit some variations on the structure of the jquery plugin. For our purpose, we will stick to famous jQuery Plugin Development Pattern. Following that pattern, I have created this plugin template to create jquery plugins:

/**
 * Your plugin name and a small description
 * Author: Name here
 * Version: 1.00
 */

(function($){

    $.fn.pluginName = function(settings){

  	// Extend our default options with those provided.
  	// Note that the first arg to extend is an empty object -
	// this is to keep from overriding our "defaults" object.

        var opts = $.extend({}, $.fn.pluginName.defaults, settings);

        return this.each(function(settings){
           var options = $.extend({}, opts, $(this).data());

           var $this = $(this);

            // do something

        });
    }

  // plugin defaults - added as a property on our plugin function
  $.fn.pluginName.defaults = {
    option_name: value
  }

})(jQuery);

No need to worry about above snippet of code if you are seeing that for the first time, I will try to explain it. First of all, we wrap the jquery namespace $ in a function and create a closure:

(function($){
  // code here......
})(jQuery);

This ensures that our plugin won’t break if there are other javascript libraries used on a page where our plugin is used. This happens because in some other javascript libraries, $ has also a special meaning like in jquery. Then as I said earlier, we create a jquery plugin something like:

$.fn.pluginName = function(){
   // code here....
}

If we want to add additional settings to our plugin that will be customizable by those who use our plugins, we pass a options/settings parameter like this:

$.fn.pluginName = function(settings){
   // code here....
}

This is useful in our case because our drop shadow plugin will allow plugin users to set these settings when using the plugin:

  • shadowColor
  • shadowLayer
  • distance

Then we see following line in the template above:

var opts = $.extend({}, $.fn.pluginName.defaults, settings);

It allows plugins users to override the default plugin settigns with their own.

jQuery has an excellent mechanism of chaining which allows you to use more than one functions/methods on given wrapped set/elements, for example:

$('selector').removeClass('class-name').addClass('class-name');

And in order to add this chaining capability to our plugin, we need to put our code like this as can be seen in the template above:

return this.each(function(){
    // code here....
});

But for the sake of plugin development pattern, I pointed out earlier, it should be modified like:

return this.each(function(settings){
   var options = $.extend({}, opts, $(this).data());
});

And finally, we should put some of our default settings for the plugin:

  // plugin defaults - added as a property on our plugin function
  $.fn.pluginName.defaults = {
    option_name: value
  }

The Drop Shadow Plugin

Now that we have seen some of the details about jquery plugin development, let’s create our drop shadow plugin. First we start off with basic skeleton of plugin as shown in the template above:

(function($){

    $.fn.dropshadow = function(settings){
        // Extend default settings
        var opts = $.extend({}, $.fn.dropshadow.defaults, settings);

        return this.each(function(settings){
           var options = $.extend({}, opts, $(this).data());
           var $this = $(this);

           //////////////////////////////////////////////
           //  plugin logic code here
           //////////////////////////////////////////////

        });
    }

   // set default option values
  $.fn.dropshadow.defaults = {
	shadowColor: '#DFDFDF',
	shadowLayer: -1,
	distance:'5px'
  }

})(jQuery);

As can be seen, everything is similar to template above except for plugin name and default options for our plugin shown at the end of the above code. We now need to move our previous code we had used to create the effect in the area where it says plugin logic code here. So here is the entire drop shadow plugin code:

(function($){

    $.fn.dropshadow = function(settings){
        // Extend default settings
        var opts = $.extend({}, $.fn.dropshadow.defaults, settings);

        return this.each(function(settings){
           var options = $.extend({}, opts, $(this).data());
           var $this = $(this);

		  $('</pre></pre>
<div class="drop_shadow_layer">').appendTo($('body')).css({</div>
<pre>
<pre>
			position: 'absolute',
			width: $this.width() + 'px',
			height: $this.height() + 'px',
			backgroundColor: options.shadowColor,
			zIndex: options.shadowLayer,
			top: ($this.offset().top + parseInt(options.distance, 10)) + 'px',
			left: ($this.offset().left + parseInt(options.distance, 10)) + 'px'
		  });
        });
    }

   // set default option values
  $.fn.dropshadow.defaults = {
	shadowColor: '#DFDFDF',
	shadowLayer: -1,
	distance:'5px'
  }

})(jQuery);

This time, the only change we made to our code is that of using option properties that we allow users to specify.

Using the Drop Shadow Plugin

Using the plugin as easy as this one line of code (that’s beauty of a plugin):

$('.shadow').dropshadow();

And since our plugin allows some settings, you can specify them like:

  $('.shadow').dropshadow({
	shadowColor: '#cccccc',
	shadowLayer: -100,
	distance:'6px'
  });

This will apply the shadow to any element that has the shadow class. Of course, you can change the selector there and/or specify a single element based on id instead of a class. You can change the class name there of course based on your elements class name.

Please note that if you are going to apply the shadow to images, you need to make sure that you wrap the code in window’s load event rather than ready handler of jQuery because getting image dimensions doesn’t work in some browsers when using the ready handler. Also, we use resize event to re-draw the shadow elements when window is resized. All the divs created for shadow effect have the class drop_shadow_layer.

$(window).bind('load resize', function(e){
   if (e.type === 'resize'){
     $('.drop_shadow_layer').remove();
   }

   $('.shadow').dropshadow({
      shadowColor: '#cccccc',
      shadowLayer: -100,
      distance:'6px'
   });
});

So that will apply drop shadow effect to any element having shadow class.

I tried to make things as easy as possible and I hope you learned something useful .

Download Drop Shadow Plugin

Drop Shadow Effect With JQuery

I am very excited  because for this post, I have created my first ever screencast that demonstrates how easy it is to actually create  the drop shadow effect with JQuery. In fact, we will be using four to five lines of JQuery code to achieve this cool effect. The shadow can be applied to just but anything not just the images. See the shadow effect in action first. Let’s see the idea behind this effect.

.

The Idea?

Absolute positioning in CSS is extremely useful allowing you to position elements just about any place on the page. This is exactly what we are going to do. For each element that is to be shadowed, we create a div and position it behind that element to create the shadow effect. The height and width of each created div is same as that of element which is to be shadowed. Note that all of that is done from JQuery code.

.

Screencast

In this video, I create the shadow effect from scratch. I recommend you to see the video in full screen for better viewing.