Injecting jQuery: Just for Fun

I’ve put together a small snippet you can enter at the top of any page. Use it to inject the jQuery library into the page, and optionally run a small script of mine which will create a small debugging tool. It’s like Firebug Lite, except much smaller and less useful.

Just type this into the address bar after you’ve loaded a page:

javascript:var i,s,ss=['http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js','http://extraordinarythoughts.com/toybox.js'];for(i=0;i!=ss.length;i++){s=document.createElement('script');s.src=ss[i];document.body.appendChild(s);}void(0);

Want only jQuery? Use this:

javascript:var i,s,ss=['http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js'];for(i=0;i!=ss.length;i++){s=document.createElement('script');s.src=ss[i];document.body.appendChild(s);}void(0);

Understanding jQuery Plugins

jQuery Logo

If you’re here, I’m sure it’s no surprise jQuery is an easy library to use. jQuery may be easy, but it still has its quirks and can be difficult for some to grasp beyond basic functionality and concepts. No worries, I’ve got a simple guide here to help break down code, that may seem like overly complex syntax, into simple thoughts and patterns that can be easily understood.

Here, we’ve got a basic plugin layout:

// Shawn Khameneh
// ExtraordinaryThoughts.com
 
(function($) {
	var privateFunction = function() {
		// code here
	}
 
	var methods = {
		init: function(options) {
			return this.each(function() {
				var $this = $(this);
				var settings = $this.data('pluginName');
 
				if(typeof(settings) == 'undefined') {
 
					var defaults = {
						propertyName: 'value',
						onSomeEvent: function() {}
					}
 
					settings = $.extend({}, defaults, options);
 
					$this.data('pluginName', settings);
				} else {
					settings = $.extend({}, settings, options);
				}
 
				// run code here
 
			});
		},
		destroy: function(options) {
			return $(this).each(function() {
				var $this = $(this);
 
				$this.removeData('pluginName');
			});
		},
		val: function(options) {
			var someValue = this.eq(0).html();
 
			return someValue;
		}
	};
 
	$.fn.pluginName = function() {
		var method = arguments[0];
 
		if(methods[method]) {
			method = methods[method];
			arguments = Array.prototype.slice.call(arguments, 1);
		} else if( typeof(method) == 'object' || !method ) {
			method = methods.init;
		} else {
			$.error( 'Method ' +  method + ' does not exist on jQuery.pluginName' );
			return this;
		}
 
		return method.apply(this, arguments);
 
	}
 
})(jQuery);

You may notice the structure I’ve provided is significantly different from others. Plugins can vary depending on usage and needs. Here, it is my goal to explain the concepts in code well enough for you to understand and author a plugin in such a way that suits you best.

So, let’s break it down!
Continue reading