user1658136
user1658136

Reputation: 119

Creating and calling jQuery Plugin

I have come across plenty of jQuery Plugin Patters (boilerplates) on this website:

Github jQuery Plugin Patterns

Nonetheless I was looking even further but I was unable to find anything that would work as I expected. My knowledge for jQuery is quite low, yet I thought I will earn the best if I start creating some small plugins for self... Just for fun and to learn more.

So for example I like this patter: Best Options Pattern

It looks clean and quite nice to me. However I am not sure why I cannot call the plugin like all other plugins that we can find around... For example backstretch JS or Make it Retina... It is called like this.

$.backstretch('path to image');

$.makeItRetina();

So I have tried everything that I thought it might work and the only way to call the plugin from that pattern above is following:

$(document).pluginName();

And I don't want to have it like that... It looks better and simplified if it's just

$.pluginName();

Anyone to show me the path / way how to do this ? I am really confused.

Upvotes: 1

Views: 85

Answers (2)

Matthew Hammel
Matthew Hammel

Reputation: 104

Try:

var plug = $(document).pluginName();

and then call plug.makeItRetina(); or plug.backstretch('path to image');

Hope this helps.

EDIT: Not correct but leaving with comment in case the lesson I learned can be learned by someone else. :)

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191729

If you want to extend the jQuery object itself (to call methods on $) don't extend $.fn, just extend $.

When you extend (add methods to) $.fn, they are called via $(selector).method rather than the $.method syntax you are looking for, which requires no special behavior with respect to JavaScript.

Upvotes: 3

Related Questions