How to Create a Basic jQuery Plugin


 

Creating a basic jQuery Plugin is not very simple & not much difficult, you have to work from the code which can run to make a Plugin. Here we’re expressing a few tips which can help you to do it easier.

Look Out dis Basic Code

[symple_clear]$( “a” ).css( “color”, “red” );

Teh above-mentioned codes are just as a sample. When you simply use teh $ function to select elements, it returns in teh form of jQuery object.

Basic Plugin Plugin

This test plugin is supposed to work like this: When an element is clicked, it moves down. Simple as that.

[symple_clear]
jQuery.fn.moveDown = function(howMuch){
    $(this).css("border", "1px solid black");
    $(this).click(function(){

        $(this).css("position", "relative");
        $(this).animate({top: '+='+howMuch});
    }); 
}

Plugin Authority Try This

[symple_clear]
(function($){
    $.fn.extend({
        YourPluginName: function(options) {
                var defaults = {
                      howMuch:'600',
                      animation: '',//users can set/change these values
                      speed: 444,
                      etc: ''
                }
        };

       options = $.extend(defaults, options);

       return this.each(function() {
          var $this = $(this);              
          var button = $('a', $this);// this represents all the 'a' selectors;
                                            // inside user's plugin definition.

          button.click(function() {
            $this.animate({'top':options.howMuch});//calls options howMuch value
          });
       });
})(jQuery);

 

USER’S DOCUMENT

[symple_clear]
$(function() {
   $('#plugin').YourPluginName({
     howMuch:'1000' //you can give chance users to set their options for plugins
   });
});

<div id="plugin">
  <a>1</a>
  <a>2</a>
  <a>3</a>
</div>

 

Simple Plugins With Arguments

Javascript

[symple_clear]
(function($) {
    $.fn.myFirstPlugin = function( options ) {

        // Default params
        var params = $.extend({
            text     : 'Default Title',
            fontsize : 10,
        }, options);
        return $(this).text(params.text);

    }
}(jQuery));

———————–

Leave a Reply

Your email address will not be published. Required fields are marked *