DevWL
DevWL

Reputation: 18840

How to write own custom jQuery plugin (Uncaught TypeError: ... not a function)

Where did I make a mistake ? Is that some syntax error ?

custom.js:

(function($){
    $.fn.marquee = function(options, callback){

        // check callback
        if(typeof callback == 'function'){
            callback.call(this);
        } else{
            console.log("secound argumnt (callback) is not a function");
            throw "callback must be a function";
            return;
        }

        //set and overwrite default options
        var defOptions = $.extend({
            option1: 10,
            option2: 'something'
        }, options);
    };

    //plugin logic here
    // ...

    return this;

}(jQuery));
//END PLUGIN

In same file now i try to run the plugin by calling:

// RUN PLUGIN with options or leave empty for defeaults
$.marquee({
    option1: 9,
    option2: 'something else'
}, function(){
    alert('some callback');
});

Then I get this error (in chrome console)... anyone knows whats the issue here?:

Uncaught TypeError: $.marquee is not a function

More details about error from the chrome console:

(anonymous function) @ custom.js:25m.
Callbacks.j @ jquery-1.11.2.min.js:2m.
Callbacks.k.fireWith @ jquery-1.11.2.min.js:2m.
extend.ready @ jquery-1.11.2.min.js:2J @ jquery-1.11.2.min.js:2

Upvotes: 1

Views: 990

Answers (1)

Amit Joki
Amit Joki

Reputation: 59232

That's because you've attached it to jQuery's prototype, $.fn. Your plugin would work right had your code been

$('some element').marquee({
    option1: 9,
    option2: 'something else'
}, function(){
    alert('some callback');
});

The plugin declared at $.fn are plugins that work on elements and has their reference of this inside the plugin.

The fix is to declare it on $ or jQuery

$.marquee = function { 
    // (...) Code here
}

Upvotes: 1

Related Questions