Home / Articles / Programming languages / Scripting languages / JavaScript / jQuery for beginners: plugins

jQuery for beginners: plugins

jQuery for beginners: plugins
 
jQuery for beginners: plugins
  • Currently 0 out of 5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Rating: 0/5 (0 votes cast)

Thank you for rating!

You have already rated this page, you can only rate it once!

Your rating has been changed, thanks for rating!

Log in or create a user account to rate this page.


As a start let us recall, why do we need plugins in the first place? The answer is - to create reusable code, of course - with a friendly interface. Let's write some code, here's a simple problem: "By clicking on the paragraph, the text should change to red".

Javascript and not jQuery

In order not to forget the ancient origin - let's start with realization in the native language - Javascript:

var loader = function () {
  // find all paragraphs
  var paragraph = document.getElementsByTagName('P');
  // go through all of them , and assign handler. 
  for (var i=0,size=paragraph.length;i<size;i++) {
    // handler
    paragraph[i].onclick = function() {
      this.style.color = "#FF0000";
    }
  }
}
// of course, all the code must run after the entire page has loaded
document.addEventListener("DOMContentLoaded", loader, false);

Live demo

This is not cross-browser code, and was written to emphasize once more the convenience of using framework.

jQuery, but not plugin, yet

Now you can simplify the code, connect the jQuery and get the following example:

$(document).ready(function(){
  $('p').click(function(){
    $(this).css('color', '#ff0000');
  })
});

Live demo

At last jQuery plugin

The task is solved, but where is the repeated use of the code? Or if we need green and not red? That's where the interesting part begins, to write a simple plugin, all you need to do is to extend the object $.fn:

$.fn.mySimplePlugin = function () {
  $(this).click(function(){
    $(this).css('color', '#ff0000');
  })
}

Let me write the same thing in a more professional manner - we need to restrict the variable $ only to our plugin, and also to return this, so we could use the call chains. To do this follow this example:

(function($) {
  $.fn.mySimplePlugin = function(){
    // plugin code ...
    return this;
  };
})(jQuery);

And now I'll give some explanations of what is happening. The code (function ($) {...}) (jQuery) creates an anonymous function, and right away calls it, passing as a parameter the jQuery object, so in the anonymous function, we can use the $, without worrying about conflicts with other libraries - because $ is now visible only to our function, that's how we get a full control of it.

Let's add an option that selects colors and we'll get a working plugin:

(function($) {
  // default value - GREEN
  var defaults = { color:'green' };
 
  // current settings, global
  var options;
 
  $.fn.mySimplePlugin = function(params){
    // if the function is called multiple times settings will be stored, and replaced if necessary 
    options = $.extend({}, defaults, options, params);
 
    $(this).click(function(){
      $(this).css('color', options.color);
    });
 
    return this;
  };
})(jQuery);

Call:

// firs call
$('p:first,p:last').mySimplePlugin();
// second call
$('p:eq(1)').mySimplePlugin({ color: 'red' });

Live demo

As a result of this plugin, each click will change the color of the paragraph to red. And because we use global variable to save the settings the second call of the plugin will change the value for all elements. You can make small changes, and separate settings for each call (example):

// current settings will be personalized for each call
var options = $.extend({}, defaults, params);

Live demo

Working with collections of objects

It's simple, just remember - this contains the jQuery object with a collection of all the elements, that is:

$.fn.mySimplePlugin = function(){
  console.log(this); // jQuery
  console.log(this.length); // number of elements
  return this;
};

If you need to process each element, write as follows:

// need to process each element in the collection
return this.each(function(){
  $(this).click(function(){
    $(this).css('color', options.color);
  });
});
 
// the previous version has a bit excessive code
// because the function click already contains too many elements 
return this.click(function(){
  $(this).css('color', options.color);
});

Again, let me remind you, if your plugin is not supposed to return anything that you haven't planed - let it return this - chain calls in jQuery are part of the magic, you shouldn't break it.

Public methods

So, we have a written cool plugin, you must give it some additional functions, for example let the color be regulated by several buttons on the site. For this we need the method "color", which will be responsible for everything. Here is an example of a ready plugin code - let's do some magic together:

// default velue
var defaults = { color:'green' };
 
// public methods
var methods = {
  // plugin initialization
  init:function(params) {
    // current settings will be personalized for each call
    var options = $.extend({}, defaults, params);
 
    return this.click(function(){
      $(this).css('color', options.color);
    });
  },
  // color change
  color:function(color) {
    $(this).css('color', color);
  },
  // reset color
  reset:function() {
    $(this).css('color', 'black');
  }
};

$.fn.mySimplePlugin = function(method){
 
  // a bit of magic
  if ( methods[method] ) {
    // if the requested method exists, we call it
    // all the parameters except the name of the method will be part of the method
    // this will also become part of the method
    return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
  } else if ( typeof method === 'object' || ! method ) {
    // if the first parameter is the object or completely empty
    // execute the method init
    return methods.init.apply( this, arguments );
  } else {
    // if nothing happened
    $.error( 'Метод "' + method + '" was not found in the plugin jQuery.mySimplePlugin' );
  }
};

Live demo

Again a small example of the use of these methods:

// call without parameters - init will be called
$('p').mySimplePlugin();
// call the method color and color reproduction as parameters
$('p').mySimplePlugin('color', '#FFFF00');
// call the method reset
$('p').mySimplePlugin('reset');

To grasp the idea about this part of the code, you only have to understand the variable arguments, and the method apply.

Event handlers

If your plugin assigns a handler, the best idea (almost always) is to assign the handler in its own namespace:

return this.bind("click.mySimplePlugin",function(){
  $(this).css('color', options.color);
});

This trick will allow you to remove all of your handlers at any time, or to call only a specific one, which is very convenient:

// calling only our handler
$('p').trigger("click.mySimplePlugin");
 
// remove all our handlers
$('p').unbind(".mySimplePlugin");

Use of the method data

If for some reason you are not familiar with the method data - I advise you to read through this and be enlightened. Simply said it's a registry data, and all the data connected to any element are better stored in it, the same rule applies to the plugins. If you need to save the plugin as it is - use data, if you need to cash - use the data, if you need to store... well, I think it's self-explanatory. Here is another example of initialization:

// function init
function() {
  var init = $(this).data('mySimplePlugin');
 
  if (init) {
    return this;
  } else {
    $(this).data('mySimplePlugin', true);
    return this.bind("click.mySimplePlugin",function(){
      $(this).css('color', options.color);
    });
  }
}

 

Read also

jQuery for beginners: selectors

jQuery for beginners: selectors

jQuery for beginners: AJAX

jQuery for beginners: AJAX

jQuery for JavaScript

jQuery for JavaScript

jQuery UI. Widgets. Dialog (Windows)

jQuery UI. Widgets. Dialog (Windows)

Post comment

basicuse.net
html5_css
106160485398655174790

Quick navigation

General navigation