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,125
  • 11
  • 54
  • 84
bernhardh
  • 2,881
  • 9
  • 38
  • 70

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,125
  • 11
  • 54
  • 84
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
  • 26,601
  • 7
  • 57
  • 86
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
  • 4