0

I have the following code:

$(document).ready(function() {
    $.fn.addRemoveButton = function() {
        alert(1);
    };

    $.addRemoveButton();
});

And I get the following error message from firebug:

TypeError: $.addRemoveButton is not a function $.addRemoveButton();

Why and how can I fix this?

Barlas Apaydin
  • 7,233
  • 11
  • 55
  • 86
bernhardh
  • 3,137
  • 10
  • 42
  • 77

3 Answers3

2

You need to define a selector, try this:

$(document).ready(function() {
    $.fn.addRemoveButton = function() {
        alert(1);
    };

    $(document).addRemoveButton();
});

Here is working jsFiddle.

Barlas Apaydin
  • 7,233
  • 11
  • 55
  • 86
1

You need to apply that to any DOM.

Example

jQuery Code

$(function()
{
    $.fn.addRemoveButton = function() {
        alert(1);
    };
    $('#letit').addRemoveButton();
});

HTML Code

<div id="letit"></div>
Dipesh Parmar
  • 27,090
  • 8
  • 61
  • 90
0

or, you can create it as a jQuery global function:

$(document).ready(function() {
    $.addRemoveButton = function() { // removed the .fn
        alert(1);
    };

    $.addRemoveButton();
});

This binds the function to the jQuery object, where you can then use it like in your original example.

See this post for the difference between jQuery.fn.method and jQuery.method

Community
  • 1
  • 1
strakez
  • 35
  • 5