Shivam
Shivam

Reputation: 2258

Variable undefined, (JQuery Plugin Development)

I am working on creating my first jQuery based plugin but I am stuck at an issue.

I receive an error stating var minHeight is undefined when I am trying to console.log it.

(function ($) {
    $.fn.something = function (options) {
        var defaults = {
            selector: '.selector',
            minHeight: defaults.selector.height(),
            speed: 200
        }
        console.log(defaults.minHeight);
    };
})(jQuery);

Upvotes: 0

Views: 384

Answers (1)

acdcjunior
acdcjunior

Reputation: 135862

It is really hard to understand what you are trying to achieve, but the way you are currently trying has some problems. You are attempting to set an object's property (defaults.selector) before the object itself (defaults) is defined.

In order to get it done, the simplest way is to pull minHeight's definition to other line. Also you might wanna take a look at jQuery's $.extend:

(function ($) {
    $.fn.something = function (options) {
       var defaults = {
            selector: '.selector',
            speed: 200
       }
       defaults.minHeight = $(defaults.selector).height();
       console.log(defaults.minHeight);

       // extend() will set the values of 'options' that are empty with default's
       var options = $.extend({}, defaults, options);
       // options.minHeight will be the height of '.selector' if no options are
       // given, or 'minHeight' if one is given as parameter
       console.log(options.minHeight);
    };
})(jQuery);

// testing code so you get what I mean
$().something({minHeight: 10});
$().something();

See the code above in action (open the console).

Upvotes: 1

Related Questions