Skip to content

Instantly share code, notes, and snippets.

@danferth
Last active May 22, 2019 22:51
Show Gist options
  • Select an option

  • Save danferth/5880804 to your computer and use it in GitHub Desktop.

Select an option

Save danferth/5880804 to your computer and use it in GitHub Desktop.
Jquery Plugin Syntax for referance

jQuery plugin syntax

Cheat sheet for creating jQuery Plugins

So you whant to flood the market with another scrolling slideshow, popup, video enabled jQuery plugin. Here is the syntax plain and simple.

  • creat your function that can be used with other libraries by wraping in anonymus function (function($){
  • name the function $.fn.myfunction(settings){
  • extend the function by defining the settings in a JSON object settings = $.extend({settingA:'defaultA',...});
  • start writing all of your code...
  • close plugin function };
  • close anonymus wrapper })(jQuery);
  • whole thing together
(function($){

    $.fn.myFunction(settings){
    
        settings = $.extend({setting_A: 'default_A', setting_B: 'default_B'...});
    
         ...code away!
    
    };

}(jQuery);

See the file for more explinations and sample plugin.


With all the cheat sheets thay are a work in progress and could contain mistakes. If you find these helpfull or find shit that is just plain wrong, please comment so I can fix.

Thanks

//wrap in anonymous function to create plugin that can be used with other libraries that may use '$' before jQuery grabs it
(function($){
//name and start plugin
$.fn.myPlugin = function(settings){
//set settings defaults with javascript object
settings = $.extend( {settingA: 'defaultA', settingB: 'defaultB'}, settings);
//can also be JSON object like so..({'setting-A':'default-A')}..keys need to be strings
//code goes here
//use settings.setting-A to referance settings...
};//end of plugin function
})(jQuery);//end or wrapper function
//........................
//sample plugin
//........................
(function($){
$.fn.sample = function(settings){
settings = $.extend({width:'800px',height:'200px'},settings);
$(this).css({
'width':settings.width,
'height':settings.height
});
};
})(jQuery);
$('.target').sample();
@danferth

Copy link
Copy Markdown
Author

jQuery Plugin Syntax

this is a reference for the syntax to create a jQuery Plugin.

  • wrap in anonymous function
  • create JavaScript object to set setting defaults
  • reference settings in plugin like so setting.mySetting use like variable
  • see sample at bottom for plugin that sets width and height of target elements with default of 800px x 200px

if you have anything to add to this just comment and I will add to it, thanks for viewing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment