Quantcast
Channel: web development tutorials » jquery
Viewing all articles
Browse latest Browse all 10

jquery multiple instances

$
0
0

jQuery multiple instances

here we learn how to apply our jQuery plug in for each element with our plugin instance .
by default JavaScript assumes each variable and object are static, if you change any where it remains stateless.
To understand this code we must aware of

  • JavaScript scope of variables.
  • jquery basics.

Download Demo

(function($){
instanceId=0;
	$.fn.my_plugin=function(options){
		//default options for our plugin
		defaultOptions={instanceData:'mahesh'};
		return this.each(function(){
		//for every element we create new instance options
		// remember here {} ,means we create empty object and extend with
		//default options
		//user options
		options=$.extend({},defaultOptions,options);
		//call the function that create new instance object of our plugin
		$.my_pluginInstanceCreater(this,options);
		});
	}
 
$.my_pluginInstanceCreater=function(target,options){
	//if given target element  don't have already instance of our plugin
	//then we create a new instance and assign it to target
	//if target elment has already instance of our plugin return it
	return target.my_plugin || (target.my_plugin=new $.my_pluginInstance(target,options));
	}
 
// this is main core plugin instance where we code every thing
$.my_pluginInstance=function(target,options){
 
	$(target).text(options.instanceData + '  ,Instance Id: '+(instanceId++))
	}
 
})(jQuery);
// function to create our own plugin scope of variables

Download Demo


Viewing all articles
Browse latest Browse all 10

Trending Articles