Creating Your First jQuery Plugin

October 30th, 2009

The first step is to extend the jQuery object with the function that we wish to add. I preferr to do this by passing the jQuery object into the function. This allow you to use the $ alias for the jQuery object. I should be noted that the standard naming conventions for jquery plugins is "jquery." plus your plugin name. So in this case it is "jquery.background.js".

$("div").background();
(function($){
$.fn.background = function(src,options) {
	alert($);
};
})(jQuery);



What the logic function actual performs is placed within loop I have added below. What this does is perform the code within it on each of the objects the jquery object selected. For example if this was how the plugin is called it will be the code within the loop will be performed on every div object.

$("div").background();

(function($){
$.fn.background = function(options) {

	return this.each(function(){
		alert($(this));
  	});
};
})(jQuery);



Now to customize the plug by sending it parameters. Below is an example first setting the defaults for the plugin. Then creating a var named options which is the default parameters extended, basically updated, by the options arguments.

(function($){
$.fn.truncate = function(options) {

	var defaults = {
		time: 300,
  		random: false
	};

	var options = $.extend(defaults, options);

	alert(options.time); // alerts 8000

	return this.each(function() {

	});
};
})(jQuery);



Add your logic to the loop and put your plugin to work. Below a super simple example that changes the background color with a simple transition.

(function($){
$.fn.background = function(color,options) {

	var defaults = {
  		time: 300,
  	};  

	var options = $.extend(defaults, options); 

	return this.each(function(){
		function onComplete()
		{
			$(this).css("backgroundColor", color);
			$(this).animate({opacity:1.0},options.time,onComplete);
		}

		$(this).animate({opacity:0.5},options.time,onComplete);
  	});
};
})(jQuery);


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="js/jquery-1.2.6.min.js"></script>
<script type="text/javascript" src="js/jquery.background.js"></script>
<script type="text/javascript">

$(document).ready(function()
{
	$("div.change").background("#FF0000",{time:1000});
});
</script>

<style type="text/css">
div{
	background: #00FF00;
	width: 100px;
	height: 100px;
	margin: 0 0 5px 0;
}
</style>
</head>

<body>
	<div class="change"></div>
    <div></div>
    <div class="change"></div>
</body>
</html>

Javascript / AJAX

  1.  
    No comments yet.
     
Post a Comment
  1. No trackbacks yet.
You must be logged in to post a comment.