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.
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 */ });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With