How to have multiple instances of jQuery plugin on single page?

Posted by James Skidmore on Stack Overflow See other posts from Stack Overflow or by James Skidmore
Published on 2009-10-23T21:05:46Z Indexed on 2012/10/27 17:01 UTC
Read the original article Hit count: 225

I'm writing a simple jQuery plugin, but I'm having trouble being able to use multiple instances on a page.

For instance, here is a sample plugin to illustrate my point:

(function($) {
  $.fn.samplePlugin = function(options) {
    if (typeof foo != 'undefined')
    {
      alert('Already defined!');
    } else {
      var foo = 'bar';
    }
  };
})(jQuery);

And then if I do this:

$(document).ready(function(){
  $('#myDiv').samplePlugin({}); // does nothing
  $('#myDiv2').samplePlugion({}); // alerts "Already defined!"
});

This is obviously an over-simplified example to get across the point. So my question is, how do I have two separate instances of the plugin? I'd like to be able to use it across multiple instances on the same page.

I'm guessing that part of the problem might be with defining the variables in a global scope. How can I define them unique to that instance of the plugin then?

Thank you for your guidance!

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery