Sunday 24 September 2017

Write your first jQuery plugin

Below jQuery plugin will help you check, if the DOM element has an attribute ?
It is very basic and straight.


//---------------------------------------
//      calling the plugin
//---------------------------------------

    $(document).ready(function () {
         if ($("input[value='xyz']").hasAttr('checked')) {
            //Do Your Stuff
         }
      } 
//--------------------------------------
//       jQuery plugin
//---------------------------------------

   (function($) {
       $.fn.hasAttr = function(attrName) {
            if($(this).attr(attrName) == undefined) return false;
            else return true;
        }
    }(jQuery));
//---------------------------------------

Understanding this - I will no  go into too much details. I'll just help you start.

1.  This is not compulsory to write. It just helps you use "$" for jQuery and not conflict with other      frameworks.
    (function($) {    }(jQuery));

2. This is the plugin code. It's very straight forward. You have passed an attribute and $.fn.YourName => give a name to your plugin,
  $.fn.hasAttr = function(attrName) {
      //your code
  }

Some more important concepts :-

a. Chaining-  In jQuery we can apply multiple functions giving "," and just appending it.

    Example -  $('#tableid').addClass("abc").attr(id);
    This code will add class to the table html element and then give you id attribute.

    Now, consider this plugin code

     $.fn.addMyClass = function (className){

           $(this).addClass(className);
                //the important part
                 return this; //this returns the handle of the table - for further action.
                //hence chaining can be performed after you plugin is called.
            }
      }

      $('#tableId').addMyClass("abc").attr("id");  //this will do the same thing

b. Default options to the plugin

      $('#tableId').addMyClass({
          ClassName: 'cde'
      });
      //cde will over write the abc class. But if not provided, abc will      be set as class

     $,fn.addMyClass = function (option){
            
             var settings = $.extend({
                  ClassName: 'abc' //default value if nothing is passed.
              }, options);

             $(this).addClass(settings.ClassName); //adding the passed class name
                 return this; //helps chaining
              }
       }

No comments:

Post a Comment