SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Evangelist silversurfer5150's Avatar
    Join Date
    Aug 2010
    Posts
    532
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    JQuery Plugin Creation

    Hi there,

    I have been checking out the following sitepoint tutorial on creating a plugin using Jquery

    http://www.sitepoint.com/how-to-deve...jquery-plugin/

    I have some Questions about the selector and the parameters.
    Say for example, I wanted to pass parameters into the plugin:
    Code:
    (function($) {
    	// jQuery plugin definition
    	$.fn.MyPlugin = function(params) {
                 
             // do something
    		return this;
    	};
    })(jQuery);
    It is as simple as $(selector).MyPlugin(someparameters)

    And conversely if the plugin takes no parameters $(selector).MyPlugin();

    Firstly is my understanding correct and secondly what if the plugin doesn't
    require a selector? What if it doesn't need to do anything to a given DOM element?

    would it be something like:

    $().MyPlugin(someparameters)
    "Persistence is the path to perfection"

  2. #2
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,183
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    More or less you are correct, the most common way for passing parameters into a plugin is by using an object which you can merge if you wish to have defaults. See the below example:

    Code JavaScript:
    (function($) {
        $.fn.myPlugin = function(options) {
            var defaults = {
                type : null,
                key  : false
            };
     
            $.extend(defaults, options);
        };
    })(jQuery);
     
    $('selector').myPlugin({
        type : 'select',
        key  : true
    });

    If you don't wish to use a selector reference all you simply need to do is remove the fn extender from the new plugin declaration like the below example:

    Code JavaScript:
    (function($) {
        $.myPlugin = function() {
            alert('foobar');
        };
    })(jQuery);
     
    $.myPlugin();
    Blog/Portfolio | Evolution Xtreme | DFG Design | DFG Hosting | CSS-Tricks | Stack Overflow | Paul Irish
    Having lame problems with your code? Let us help by using a jsFiddle

  3. #3
    SitePoint Evangelist silversurfer5150's Avatar
    Join Date
    Aug 2010
    Posts
    532
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks SgtLegend that really clears things up
    "Persistence is the path to perfection"


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •