Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 274
user319940 Avatar asked Mar 19 '23 16:03

user319940


1 Answers

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 */ });
like image 196
Rory McCrossan Avatar answered Mar 28 '23 22:03

Rory McCrossan