user319940
user319940

Reputation: 3317

jQuery $.fn. function not defined

I've been making my first tiny jQuery plugin - I was using the javascript with a standard function but decided to bundle it up in to a jquery plugin with a few options.

Here's a slim down version of my jquery code:

(function($) {

        $.fn.responsiveNav = function( options ) {

            // Establish our default settings
            var settings = $.extend({
                selector         : '.responsive-nav'
            }, options);

            $( " " + settings.selector + " ul li" ).has( "ul" ).each(function() {
                $(this).addClass('responsive-nav-dropdown');
            });
            $( ".responsive-nav-dropdown" ).click(function() {
                $("ul",this).toggle();
            });

        }

    }(jQuery));

I'm then calling this function in document ready by doing the following:

$( document ).ready(function() {
    responsiveNav();
});

But this is leading to a function not defined error. I'm guessing that this is some sort of scoping issue but I haven't been able to find anything to help me rectify the issue.

Upvotes: 4

Views: 6171

Answers (3)

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93173

(function($) {
   ///

    })(jQuery);

And not

(function($) {
   ///

    }(jQuery));

Another thing: don't pass selector in setting. If so, what is the utility of jQuery.

The Jquery object in your plugin is this:

.each(function(i,e) {}) 
// known that e is the current element in your loop
    $.fn.responsiveNav = function( options ) {
        var this=that; 
        var settings = $.extend({selector: '.responsive-nav'}, options);
    $(that).has( "ul" ).each(function(i,e) {
        $(e).addClass('responsive-nav-dropdown');
    });
    $( ".responsive-nav-dropdown" ).click(function() {
        $("ul",this).toggle();
    });
}

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337560

The $.fn construct is used to define a method on the jQuery object. Therefore you need to use your plugin like this:

$('#myElement').responsiveNav();

Alternatively you can make it a method off the jQuery variable itself:

$.responsiveNav = function( options ) { // note: no .fn
    // your code...
}

// to call it:
$.responsiveNav({ /* options */ });

Upvotes: 5

Barmar
Barmar

Reputation: 780798

You need to call it like:

$("selector").responsiveNav();

Upvotes: 0

Related Questions