5

I have a question which at the first glance might seem to be stupid. I got problem figuring it out and whenever I use it, nothing really happens. I have a plugin in jQuery written by myself which is like this:

(function(){
$.fn.myPlugin = function(options){
var options = $.extend({
firstParameter : null;
}
// the rest of the plugin
})(jQuery)

But when I call it from an HTML file, like this: ("#object").myPlugin(2);, it fails to work (note the parameter that I have passed). But if I skip the argument and call it like this: ("#object").myPlugin();, it all works. What is the problem?

Thanks in advance

2
  • Well, options is meant to be an object, and you're not extending anything... Double check the manual again, you're missing something. Commented Jun 16, 2013 at 4:20
  • you overwrite options in the first line. Commented Jun 16, 2013 at 4:22

2 Answers 2

30

You want this:

(function($) {
    $.fn.extend({
        myPlugin: function(options) {
            var defaults = {
                something: 23,
                otherThing: 'hello'
            };

            options = $.extend(defaults, options);

            console.log(options.something);
            console.log(options.otherThing);
        }
    });
})(jQuery);

Now this should work to override the something option (don't forget to pass an object):

$('#object').myPlugin({something: 17});
Sign up to request clarification or add additional context in comments.

3 Comments

Accepting my answer would be better than thanking me in a comment.
Oops! it is possible when my reputation rises above 15
Isn't it best practice to omit the var when setting the optionns variable a second time? options = $.extend(defaults, options);
0

You define a function with no parameter function() {} then you pass the jQuery to it. It may be the cause of problem.

(function(){
  // nothing is the $ here
  $.fn.myPlugin = function(options){
    var options = $.extend({
     firstParameter : null;
    }
  // the rest of the plugin
 })(jQuery)

You should change to

(function($) {})(jQuery) 

and I think it will work. Hope this help

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.