Posts

Showing posts with the label how-to

How to create a jQuery plugin

I tend to write everything i do in JavaScript as a jQuery plugin. Even if it's mostly useless, i think it's a convenient way to encapsulate the code. In this post I'll show how to make a simple plugin that replaces the background color of an element when the mouse hovers over it. In real life you would probably want to do this with CSS pseudo-classes . Step 1 - Get ready All plugins i write always starts with the same template: (function($){ $.fn.backgroundHover = function(options) { return this.each(function () { // Code goes here }); }; })(jQuery); Line 1 and 7 are only there to protect from $-function overloading by using variable scoping . On line 2 the plugin function is defined in the prototype of jQuery. fn is just an alias for prototype . Since a plugin can be applied to many DOM nodes in one call, we must loop through every element on line 3. Step 2 - Get Set Now we just need to write the actual code for the plugin. First we gonna a...