0

I'm trying to create a simple plugin that I can call by both: $.myPlugin() and $('something').myPlugin()

Heres the code:

(function($) {
  $.fn.myPlugin = function(item) {
    return this;
  };

  $.myPlugin = function(item) {
    return $.fn.myPlugin(item);
  };
}(jQuery));

This works when called either way mentioned above.

However, calling $.myPlugin().hide() does not work. Any chained methods are failing.

Heres a simple JSBin I made showing the issue

Why?

1
  • fn is a shortcut for prototype, you're creating different instances and expecting them to somehow be the same ? Commented Nov 16, 2014 at 5:06

1 Answer 1

1

You should return $(this), not jquery this:

(function($) {
    $.fn.myMethod = function() {
      this.append('<p>MY METHOD</p>');

      return $(this);
    };

    $.myMethod = function() {
      return $.fn.myMethod();
    };
}(jQuery));

$(function () {
    // Moment of truth
    $('.output').myMethod().hide('slow');

    $('h1').click(function(){
      $('.output').myMethod().hide();
    });
});
Sign up to request clarification or add additional context in comments.

2 Comments

I'm not sure what you mean by "return element, not jquery function". I know it works fine by calling $('.output').myMethod().hide() but I want to be able to call it by $.myMethod(), similar to how you can do $.each(item, function(){...})
Then instead return this; use return $('.output'); at 3rd line of you snippet

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.