parm530
10/15/2018 - 4:11 PM

Creating jQuery Plugin

How to ...

Basics

  • $('a').css('color', 'red');
  • Using the $ means to return a jquery object
  • This object contains MANY methods (such as the .css, .click(), etc....), how?
    • These methods are inherited from $.fn object
    • If you plan to create your own methods, you will STILL NEED TO HAVE THE ABOVE MENTIONED METHODS!
  • To create your own plugin, means to add another function to the $.fn object!
    • $.fn.pluginName = function() {};
    • You can then call it on any element(s): $("a").pluginName();
    • Do not add extra functions within your plugin using the $.fn, control functions with if statements.
  • TIP: To make your new jQuery plugin chainable you will need to return the object
    • Can be returned with return this
    • Also, since your object will contain references to other DOM elements, you might want to use: return this.each(function() {})

Structure

  • mkdir jquery_plugin
  • cd jquery_plugin && mkdir css && mkdir js && mkdir images && touch index.html
  • project structure should now look like:
    • jquery_plugin
      • css
      • images
      • js
      • index.html.erb

Adding Jquery to the project

  • link to jquery-1.9.1.min.js [here](https://gist.githubusercontent.com/jinthagerman/5 187dfae5bce5c6f208a/raw/176a5d0fc2ea6b7c6db0deb238d657844e292a27/jquery-1.9.1.min.js)
  • copy the code into js/jquery-1.9.1.min.js
  • add another js file: touch js/jquery.hello-world.js

HTML file

  • index.html add the source to load your js files at the bottom of the html page just before the closing body tag :
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/jquery-hello-world.js"></script>

jQuery Plugin Structure

  • Traditional jQuery plugin
(function($) {
  $.fn.helloWorld = function() {
    // contains js code
    return this.each(function() {
      $(this).text("Hello World!");
    }
  }
}(jQuery));
  • IFFE is used to wrap your code into a local scope, to keep it separate from other js on your page
  • $.fn is jQuery's way of allowing you to define your own plugin, in this case is named helloWorld
    • So now you can attach your jquery function to an element and the code within the helloWorld function will execute
    • Since you are calling this method through jQuerying for a DOM element, this will refer to the actual jquery object, and once you iterate through the object, you will need to refer to it by using $(this).
    • In order to make your plugin chainable to other jquery methods you will need to return the results of the plugin as it loops through the DOM elements.

Invoking the plugin

  • You either create a new js file to wrote js code that is not related to the plugin or attach your js code to a sript tag in your html file below your loaded plugins.
$(document).ready(function() {
  $("div").helloWorld();
)};
  • Reload the page to see the changes!

Passing in an argument

(function($) {
  $.fn.helloWorld = function(arg1) {
    return this.each(function() {
      $(this).text(arg1)
    });
  }
}(jQuery));

// Call it in the script files as ...
$().helloWorld("Whatever");

Complete Customization

  • Need to add default args?
  • More customization
(function($) {
  $.fn.helloWorld = function(options) {
    // ESTABLISH SETTINGS
    
    var settings = $.extend({
      text: 'Hello WORLD!',
      color: null,
      fontStyle: null
    }, options);
    
    return this.each(function() {
      $(this).text(settings.text)
    });
  }
}(jQuery));


$().helloWorld({text: "Hi!"})
// Need to pass the text arg as an object

// Save your defaults in a variable to prevent them from being over-written
(function($) {
  $.fn.helloWorld = function(options) {
    // ESTABLISH SETTINGS in a variable
    var defaults = {
      text: 'Hello WORLD!',
      color: null,
      fontStyle: null,
      callbackName: function() {}
    }
    
    var settings = $.extend({}, defaults, options);
    
    return this.each(function() {
      $(this).text(settings.text)
    });
  }
}(jQuery));


  • A settings object has been declared, so that when the plugin is invoked devoid of any args , it will use the default text due to $.extend({})

Adding Callbacks

// in the settings object:
var settings = $.extend({
  text: "Hello!",
  complete: null
}, options);

  • complete is a function that will be executed once the helloWorld plugin runs
  • You will need to check if it is indeed a function: $.fn.isFunction
return this.each(function() {
  if($.isFunction(settings.complete)) {
    settings.complete.call(this);
  }
});

//...

// To invoke a function
$().helloWorld({
  text: "Hello",
  complete: function() {
    alert("Plugin Activated!");
  }

});


Adding Methods

  • In order to be able to save your plugin to a variable and call methods on it, use the following:
(function($) {
  
  // PUBLIC METHODS
  // Need an initialize method
  this.initialize = function() {
    return this;
  }
  
  // Add your methods here
  this.methodName = function(args) {
    // stuffs in here
  }
  
  return this.intialize();
  
}(jQuery));