HTML, HTML5, JavaScript, jQuery

How to Create jQuery Plugins

Naming Convention

jquery.pluginName.js for non-minify version
jquery.pluginName.min.js for minified version
$.fn is an alias of the jQuery.prototype JavaScript property
To manipulate specific elements, use .each()

The Scaffolding

(function($) {
	// attach `Say` to jQuery plugin hook $.fn
	$.fn.Say = function(options) {
		
		// default options
		var default_option = {};
		
		// accepting options & extend the options
		var settings = $.extend( default_option, options );
		
		return this.each(function() {
			// Do something to each item
		});
	}
})(jQuery);

Do something with `Say` plugin

(function($) {
	// attach `Say` to jQuery plugin hook $.fn
	$.fn.Say = function(options) {
		
		// default options with key `what` and it's value `foo`
		var default_option = {
			what : 'foo'
		};
		
		// accepting options & extend the options
		var settings = $.extend( default_option, options );
		
		return this.each(function() {
			// set text to element
			if(settings.what)
			{
				// set text
				$(this).text( settings.what );
			}
			
		});
	}
})(jQuery);

Use it!

The Structure


|–index.html
|–/js
   |–/js/tuts.js
   |–/js/jquery.Say.js
   |–/js/jquery-1.8.3.min.js

The index.html
<!DOCTYPE html>
<html lang="en">
    <body>
		<button onclick="sayDefault()">Say Default</button>
		<button onclick="say()">Say Something</button>
		
		<p>hey</p>
		
		<script src="js/jquery-1.8.3.min.js" type="text/javascript"></script>
		<script src="js/jquery.Say.js" type="text/javascript"></script>
		<script src="js/tuts.js" type="text/javascript"></script>
    </body>
</html>
The js/tuts.js
function say()
{
	$('p').Say({'what':'someting else'}); // overwrite default value
}

function sayDefault()
{
	$('p').Say();
}

Result

Default

Using Default Option

Overwritten options.what

Overwrite options

Leave a Reply

Your email address will not be published. Required fields are marked *

ten − one =