In the last article I talked about MVC and doing some nifty Ajax functionalities with jQuery. In this article I will go over jQuery plugins, what they are and how to create them.

jQuery Plugins

jQuery has a plugin architecture which allows you to package up commonly used functions into a plugin. Chances are if you have a complex JavaScript function, someone has more than likely written a plugin to handle that particular functionality. The jQuery.com site has an extensive plugin library and it can sometimes be fun to browse through it to see what people have come up with.

Plugins are fairly easy to write, once you have gotten the basics of jQuery down. Here is a tooltip plugin that I wrote in just a few minutes.

1: (function ($) {

2: $.fn.tooltip = function (options) { // make sure to name the function

3: // the same as your tooltip

4: var methods = {

5:

6: //initialize stuff

7: init: function (options) { },

8:

9: //destroy and clean up

10: destroy: function () {

11: return this.each(function () {

12: $(window).unbind("tooltip");

13: })

14: }

15: };

16:

17: // default settings if they aren't passed in

18: var settings = {

19: 'backgroundColor': 'red',

20: 'color': 'blue',

21: 'toolTipText': 'Hi',

22: 'fontWeight': 'bold'

23: };

24:

25: // add the settings into the options

26: return this.each(function () {

27: if (options) {

28: $.extend(settings, options);

29: }

30:

31: var $this = $(this);

32: $this.mouseenter(function (event) {

33: $this.css("color", settings.colorEnter);

34:

35: // if the div#toolTip isn't in the DOM, create a new one

36: if (!$("#toolTip").length) {

37: // create the element

38: $('

')

39: // set the text to passed option

40: .html(settings.toolTipText)

41: // from the style sheet

42: .addClass("toolTip")

43: // insert the div into the DOM just after $this

44: .insertAfter($this)

45: // position the div

46: .css({ "left": $this.width(),

47: // set the backgroundColor

48: "backgroundColor": settings.backgroundColor,

49: // set the font

50: "fontWeight": settings.fontWeight,

51: // set the color

52: "color": settings.color

53: });

54: }

55: $("#toolTip").fadeIn(500);

56: });

57:

58: $this.mouseleave(function () {

59: $this.css("color", settings.colorLeave);

60: $("#toolTip").fadeOut(500);

61: });

62: });

63: };

64: })(jQuery);

It's not a pretty thing, or even that functional, but it does show off how fast you can write a plugin. Let's take a look at how this plugin is implemented.

1. In the tag of your page include the references to your jQuery and JavaScript files.

1: