Joseph
Joseph

Reputation: 859

How can I pass a variable from one .js file to another .js?

I have a Symfony application with a menu that creates lashes and use a .js file to load into a div the ulr pointed to each menu option using the load () method. This .js is a variable that acts counter to reference each created tab. This idea can be seen in this example:

http://jsfiddle.net/JMMS_85/o7610t24/

$("#tabs-"+tabCounter).load($(this).attr('href'));

The URL that is loaded into the div has other links, so I created another .js file to block the original link to "preventDefault ()" and I have to reload these links in it earlier div, that is display the url of the new link in the same div, so I have to use the variable counter another .js file on it to know what is the actual div selected.

file1.js

 $(document).ready(function () {
$("#tabs").tabs();
   var tabCounter = 1;
   var cont =1;

        //Code creating the tabs omitted
 $(".container div a").on("click",function(event) {
    event.preventDefault(); 

        tabTitle = $(this).attr("title"),
        addTab();
        $("#tabs-"+tabCounter).load($(this).attr('href'));
        tabCounter++;
        $("#tabs").tabs({active: $('.ui-tabs-nav li:last').index()});
  });
 });

file2.js

$(document).ready(function () {

       $("a").click( function(event)
        {
        event.preventDefault();            

        $("#tabs-"+tabCounter).load(this.href);
    }); 

My problem is how to use the counter variable first .js file to another file.

Upvotes: 5

Views: 9194

Answers (2)

Vic
Vic

Reputation: 8991

You can also save the variable in the DOM using jquery data

For example:

Setting the initial value

$('#tabs').data('counter', 1);

Retrieving the value

var tabCounter = $('#tabs').data('counter');

Incrementing the value

var tabCounter = $('#tabs').data('counter');
$('#tabs').data('counter', ++tabCounter);

Demo

http://jsfiddle.net/o7610t24/3/

Upvotes: 1

Daniel Moreira
Daniel Moreira

Reputation: 437

You can create the variable outside of functions.

Here you can see how JavaScript Scope works: http://www.w3schools.com/js/js_scope.asp

Upvotes: 4

Related Questions