loading jQuery local copy if CDN unavailable

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.8.0.min.js"><\/script>')</script>

Using jQuery and jQuery ui with Zend Framework

talkin' jquery ui
Image by "Cowboy" Ben Alman via Flickr


For those jQuery fanatics like me wants to jQuery enabled in their Zend framework application, zf provides view and form helpers through it ‘extras’ library, also it is handy to enable.

At Bootstrap class add the following initialization method like below:

* init jquery view helper, enable jquery, jqueryui, jquery ui css

protected function _initJquery() {

$view = $this->getResource('view'); //get the view object

//add the jquery view helper path into your project
$view->addHelperPath("ZendX/JQuery/View/Helper", "ZendX_JQuery_View_Helper");

//jquery lib includes here (default loads from google CDN)
$view->jQuery()->enable()//enable jquery ; ->setCdnSsl(true) if need to load from ssl location
     ->setVersion('1.5')//jQuery version, automatically 1.5 = 1.5.latest
     ->setUiVersion('1.8')//jQuery UI version, automatically 1.8 = 1.8.latest
     ->addStylesheet('https://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/ui-lightness/jquery-ui.css')//add the css
     ->uiEnable();//enable ui


At the <head> section of your document or at layout.html, to enable jQuery at your each pages just echo like below:


echo $this->jQuery();


So you will have jQuery and jQuery ui files added into your document section like as always:

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/ui-lightness/jquery-ui.css" type="text/css" media="screen" />

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>


N.B: in order to use ZendX library under extras/library/ZendX, the ZendX directory path should be in your php include_path or alternatively can SymLink the ZendX directory under your /application/library/


My Talks at phpXperts Seminar 2010

My recent talks on JavaScript at phpXperts Seminar 2010 : “Beauty of Web“, the biggest tech seminar at Dhaka.


My topic titled “JavaScript Wash” covered the followings:

  • Common JS issues
  • JS in Mobile Application Development
  • Interactive UI samples
  • Open Source JS Libraries
  • The High-Performance JS Mantra
  • JavaScript Development Tools

If you liked this talk then rate this talk

Cheers! 🙂

jQuery Plugin Authoring – Step by Step


If you interested in JavaScript and jQuery plugin development then this one is for you(who have at-least jQuery plugin usage)


1. Add a new function property to the jQuery.fn object:

jQuery.fn.myPlugin = function() {

// plugin goes here


jQuery.fn is shortcut form of jQuery.prototype

2. Wrap up it with a self executing closure.

(function( $ ){
$.fn.myPlugin = function() {

// plugin goes here

})( jQuery );

$ in place of jQuery
it’s a best practice to pass jQuery to a self executing function (closure) that maps it to the dollar sign
so it can’t be overwritten by another library in the scope of its execution.

3. In the immediate scope of the plugin function, the this keyword refers to the jQuery object the plugin was invoked on.

(function( $ ){
$.fn.myPlugin = function() {

this.hide(); //the this keyword is the jQuery object of the DOM element on which you are pluging-in

})( jQuery );

4. jQuery selector query can match zero, one or more elements. This scenarios need to be considered when designing plugin

$.fn.myPlugin = function() {

//each() provides implicit iteration


5. Method chaining are a required behavior. Most cases We need to return a jQuery object from all plugin methods.

$.fn.myPlugin = function() {

return this.each(function(){
var $this = $(this);//have the jQuery object of the invoked element cahced for further use


With this we can chain our plugin method with built-in methods like

$('div').myPlugin().css('color', 'red');

6. Make your plugin configurable and put some default options too

$.fn.myPlugin = function(options) {

var defaults = {
 speed: 30, //some test data options here
 duration: 2000,
 frequency: 10000,
 spread: 3
 }; //default options

//inherit from provided configuration (if any)
var options = $.extend(defaults, options);

return this.each(function(){

    var $this = $(this);
    //more stuffs goes here

7. Add some more functions

$.fn.myPlugin = function(options) {

var defaults = {
 speed: 30,
 duration: 2000,
 frequency: 10000,
 spread: 3
 }; //default options

//inherit from provided configuration
var options = $.extend(defaults, options);

return this.each(function(){

    var $this = $(this);

    //some more functions added here
    var function1 = function(){};
    var function2 = function(){};

   function1(); //call functions to perform


8. Namespacing

Properly Namspacing your plugin assures that your plugin will have a very low chance of being overwritten by other plugins or code living on the same page.

9. Documentation
In-file documentation should be prepended to each function or method definition in proper format.

10. Example plugin:

A demo “Shake an Element” plugin created for more understanding of jQuery plugin structure which can be download from here 🙂

11. Usage

All plugin files must be named jQuery.myPlugin.js where myPlugin is the name of the plug-in.

Append your jQuery.myPlugin.js at the head section of your HTML Document.

<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jQuery.myPlugin.js"></script>
$(document).ready(function($) {

12. Optional but useful 🙂

Compress and Minify your plugin codes


This JavaScript compressor/obfuscator by Dean Edwards is used to compress the jQuery source code. It’s available as a web-based tool or as a free download. The resulting code is very efficient in file size, at a cost of a small increase in execution time:




Created by Douglas Crockford, JSMin is a filter that removes comments and unnecessary white space from JavaScript files. It typically reduces file size by half, resulting in faster downloads:


Using Google’s CDN to load JavaScript libraries

For rich Ajax web applications page loading time suffers from loading JavaScript libraries such as JQuery, MooTools, Prototype etc..  Most of them are larger than 50KB in size and if you are in need to combine libraries then you are adding 100KB+ to your page loads.

Also your web server will experience delivery of your own hosted JavaScript libraries across distinct geographical requests. You can easily offload your server for those files.

Assuming all possible ways to improve JavaScript libraries loading time, Google’s CDN aka Google Libraries API can be a good solution.

Why Google CDN? Why not my own server?

  • The Google Libraries API is a content distribution network and loading architecture for the most popular, open-source JavaScript libraries.
  • Google’s huge CDN (content delivery network) can deliver the file much. Since Google has large data centers all over the world, these files will be served from data centers geographically closer to your users. This helps to reduce network latency and add to reliability, scalability and so on.
  • The more sites that include Google’s google.load() API the greater the chance that a user has already has the file cached, thus enabling your site to load faster as the script will not need to be downloaded.
  • You save bandwidth as you no longer have to serve the file(s).
  • The versioning system that Google has created makes it effortless to include specific versions of these libraries.

All you need to do is make a Google’s Libraries API call google.load() like:

<script src="http://www.google.com/jsapi" type="text/javascript"></script>

google.load("chrome-frame", "1.0.2");
google.load("dojo", "1.5");
google.load("ext-core", "3.1.0");
google.load("jquery", "1.4.2");
google.load("jqueryui", "1.8.4");
google.load("mootools", "1.2.4");
google.load("prototype", "");
google.load("scriptaculous", "1.8.3");
google.load("swfobject", "2.2");
google.load("yui", "2.8.1");
google.load("webfont", "1.0.6");


Minor Drawbacks

  • You’re dependent on the CDN infrastructure. If they are down, your website will be hardly usable, too.  But that case u have to write extra codes to check the desired library loaded or not.
  • You cannot influence bandwidth and carriers of the delivery provider’s network.

Reference: http://code.google.com/apis/libraries/devguide.html#AjaxLibraries



Ajax with jQuery.ajax() – jQuery API

Before approaching Ajax, I must say that I have seen lots of newbie programmer who are lil bit confused about “What is Ajax?”

But before digging into Ajax, lets review the non-common sense about Ajax

Ajax is  –

a) Not A Programming language 😦

b) Not a pattern

c) Not a Library itself

d) Not a framework itself

e) Not a tool itself

f) Not a function

g) Not a Technology itself, but a group of technologies.

Surprisingly some big guys call Ajax is a programming language!!!! WTF!

Interestingly  from an article at MacWorld: View that portion as Image

The above MacWorld article was written by Michael DeAgonia, Computerworld LOLz!!!

Let’s get into the real story of Ajax

Ajax (shorthand for asynchronous JavaScript and XML) is a programming technique or approach used on the client-side to retrieve data from the server asynchronously in the background without interfering with the display and behavior of the existing page. Data are usually retrieved using the XMLHttpRequest object. Despite the name, the use of XML is not actually required, nor do the requests need to be asynchronous.

AJAX requests are usually faster than regular page loads and allow for a wealth of dynamism within a page. 😀

Now come to the point, we talking about Ajax with jQuery and I am assuming that you have some idea of how to use jQuery.

The jQuery library has a full suite of AJAX capabilities. The functions and methods therein allow us to load data from the server without a browser page refresh.

jQuery.ajax() (Perform an asynchronous HTTP (Ajax) request.)

type: "POST", //default is "GET" HTTP request method
url: "myProject/myajax.php", //url(String)
data: "call=login&user=foo&pass=bar", //data form of an url query string
timeout: (60*1000), //timeout (in milliseconds) for the request

//function to be called if the request fails.
error: function(XMLHttpRequest, textStatus, errorThrown){
//here goes the error handler codes
//function to be called if the request succeeds.
success: function(data, textStatus, XMLHttpRequest){
//here goes the successful response handler codes
//will have the retrieved server response within this function

Sounds cool 😀

Lets make our jQuery Ajax more handy by using some sort of ajax settings, A default settings can be set Globally for any option with $.ajaxSetup().


url: "myProject/myajax.php", //my page to process
global: false,
timeout: (60*1000), //set timeout for all your ajax requests
cache: false, //say no to cache 😦
contentType: 'application/x-www-form-urlencoded', //is default actually(no need)
type: "POST" //if you love to post always
error: function(){ myDefaultErrorHandlerFunc(); } //set your default error handler
//The avobe setting will act like your global jQuery.ajax() settings throughout the page
//Now simple making ajax requests like below
data: {'name': 'Tonu'}, //key value paired (JSON style) or can like "call=login&name=Tonu"
success: function(xh){}

Awesome 🙂

So using $.ajaxSetup() once, you can place your ajax shortly like above $.ajax({data:”queryString”});  in your code wherever it requires.

Some more jQuery.ajax() usage example:

Load and execute JavaScript file

   type: "GET",
   url: "test.js",
   dataType: "script"

Sends an xml document as data to the server. By setting the processData option to false, the automatic conversion of data to strings is prevented.

var xmlDocument = [create xml document];
   url: "page.php",
   processData: false,
   data: xmlDocument,
   success: handleResponse

Cheers! 😀

What? Boared?!!! Why not take a deep breath and lough out loudly.. 😉

inArray in JavaScript

First of I would like to say that JavaScript doesn’t provide inArray or in_array method to check if a value exists in an array like php do PHP: in_array 😦

Well we have some good options instead 😀

But before using some custom inArray method, you better know that if you are a jQuery freak then this post is not for you because jQuery have a nice utility jQuery.inArray() – jQuery API

Yeah! we are talking about raw and plain JavaScript implementation of in_array in JavaScript.

For this we are going to add a inArray prototype method into Array class of JavaScript using simple linear search inside that method like below:

Array.prototype.inArray = function (value)
 // Returns true if the passed value is found in the
 // array. Returns false if it is not.
 var i;
 for (i=0; i < this.length; i++)
 if (this[i] == value)
 return true;
 return false;

Awesome! right 😀

Now we will use it in terms of JavaScript feature as we have already added inArray method as Array class method

var testArr= ["Shrek","Feona","Donkey"];
//use of inArray
   document.write('Are we there yet!!!!');
   document.write('Thank God!!!');

Here with our inArray prototype method implementation we are able to access inArray using DOT(.) with the given array object where most of the in_array methods takes main array as haystack and a value as needle such as in_array(search_value,array) .

This function should work fairly well on relatively small lists of items. For a larger array, a binary search function may be more appropriate.

In this way you may implement some more handy javascript prototype method.

Cheers! 🙂