user1002039
user1002039

Reputation: 860

JQuery Accessing Variables in a Plugin

How can I access and set variables in a plugin from document ready. I have found some related questions here on Stack Overflow but they didn't help me understand how this can be done.

(function($){
   $.fn.myPlugin = function(){
      var myVar1 = true;
      var myVar2 = true;
      var myVar3 = true;

      ....
      
      if(myVar1 == true){
         // do something
         ...
      }

      ....
   }
})(jQuery);

<script type="text/javascript">
   $(document).ready(function() {
      $.fn.myPlugin.myVar1 = false;
   });
</script>

Upvotes: 1

Views: 2104

Answers (3)

Andrea Turri
Andrea Turri

Reputation: 6500

Why you need to call it outside the plugin? Put your variable as Boolean option, than if true or false you build a different function... When you will use the plugin in a separate file you will write:

$(document).ready(function() {
      $('#id').myPlugin() {
         //options
      }
   });

in this way if in your option your variable will be set to true or false it will execute two different functions...

Btw if you need to call a variable outside the plugin this is the way:

$('#id').data('myPlugin').option.foo;

Upvotes: 1

Darcy
Darcy

Reputation: 5368

Use this instead of var:

this.myVar1 = true;
this.myVar2 = true;

....

Upvotes: 4

kgaddy
kgaddy

Reputation: 48

http://stefangabos.ro/jquery/jquery-plugin-boilerplate/

There are some examples on how to use public properties and methods in a plugin.

Upvotes: 1

Related Questions